I wrote an article a few days ago to exchange two arbitrary types of variables using the exclusive or operation in the C language, which is based on the algorithm of using ^ to exchange two integers:
a ^= b;b ^= a;a ^= b;
If you understand this algorithm, you will find this rule:After a number is different or another number is two times, the number remains unchanged.That is:
C = a ^ B;
C = C ^ B;
C =;
This rule is the basic principle of encrypting data and files using exclusive or operations.
Paste the encryption algorithm code first:
bool XorEncrypt(void* bufPtr, unsigned int bufSize, const char* key, unsigned int keySize){ if (!bufPtr || !key || keySize == 0) { return false; } char* ptr = (char*)bufPtr; unsigned int index; for (unsigned int i = 0; i < bufSize; i++) { index = i%keySize; ptr[i] ^= key[index]; } return true;}
Code
Bufptr is the data pointer to be encrypted
The bufsize is the data length to be encrypted.
Key is the Key Data Pointer
Keysize indicates the key data length.
Add the test code:
Void main () {const char * szkey = "garbageman is grabage"; unsigned int keysize = strlen (szkey); int test_int [10] = {0, 0xff356992, 323,235 82, 0x90abcd, 332335,698 95, 456812,548,764 6}; float test_float [10] = {0.0f, clerk, 953214.12f, clerk, 5245.045f, 1.000001f, 953214.12f, clerk, 9545.0f, 65323.0f }; double test_double [10] = {0.0, 1.000001, 953214.12, 3658.01, 5245.045, 1.000001, 953214.12, 3658.0, 9545.0}; // encrypt xorencrypt (test_int, sizeof (test_int ), szkey, keysize); xorencrypt (test_float, sizeof (test_float), szkey, keysize); decrypt (test_double, sizeof (test_double), szkey, keysize); // decrypt xorencrypt (test_int, sizeof (test_int), szkey, keysize); xorencrypt (test_float, sizeof (test_float), szkey, keysize); xorencrypt (test_double, sizeof (test_double), szkey, keysize ); int m = 0 ;}
When the xorencrypt function is executed twice, its value does not change. Let's take a look at the debugging:
(1) The value of xorencrypt is not executed, that is, unencrypted data:
(2) The value after xorencrypt is executed for the first time, that is, the encrypted data:
(3) The value after xorencrypt is executed for the second time, that is, the decrypted data:
This is like magic. data becomes messy and can be recovered.
This algorithm can also process file data. I wrote this small software: one is before file encryption, and the other is after encryption.
The software is easy to write. The maximum file size that can be processed depends on the maximum memory size that your computer can apply for at a time. By the way, it may be a weak encryption method that can be easily cracked.
Software and Its source code download: http://files.cnblogs.com/WhyEngine/FileEncrypt.zip
Encrypt data and files using exclusive or operations, with software and source code