1. 异或运算
二进制运算符^对两个操作数逐位进行比较。对于每个位,如果操作数中的对应位有一个为1(但是不都为1),那么结果为1(用真/假来描述,如果两个两个操作数中有一个为真,但不都为真,那么结果为真)。
因此:
(10010011) ^ (00111101)
= (10101110)
而且异或运算还拥有交换律,结合律:
A ^ B = B ^ A
A ^ B ^ C = (A ^ B) ^ C = A ^ (B ^ C)
A ^B = C ==> A = B ^ C; B = A ^ C
两个相同的数运算结果为0:
A ^ A = 0
0 ^ num = num
1 ^ num(BITE) = ~num(BITE)
0xffffffff ^ INT = ~INT
2. 文件加密解密思路
加密:
a). 定义一个char型字符串KEY作为加密密匙
b). 读取文件in.dat
c). 将in.dat按字节读出,与KEY进行异或(^)操作,作为加密后的字符
d). 加密后的字符,输出到out.dat
in.dat和out.dat分别为加密文件和加密后的文件名称,可随意。
解密:
解密操作只需将out.dat再和KEY异或一次,便恢复到了初始状态。
实例代码:
#include <iostream>
#include <fstream>
const int Key = 0xaf7; //密匙
bool FileConvert(char szOldFile[], char szNewFile[])
{
std::ifstream pOldFile;
std::ofstream pNewFile;
char cTemp;
if (NULL == szOldFile || NULL == szNewFile)
{
return false;
}
pOldFile.open(szOldFile, std::ios_base::in | std::ios_base::binary);
if (!pOldFile.is_open())
{
return false;
}
pNewFile.open(szNewFile, std::ios_base::out | std::ios_base::binary);
if (!pNewFile.is_open())
{
pOldFile.close();
return false;
}
//一定要先读,然后做文件末尾判断
cTemp = pOldFile.get() ^ Key;
while (!pOldFile.eof()) //判断是否到了文件末尾
{
pNewFile.put(cTemp);
cTemp = pOldFile.get() ^ Key;
}
pOldFile.close();
pNewFile.close();
return true;
}
int main()
{
char srcFile[FILENAME_MAX];
char dstFile[FILENAME_MAX];
std::cout << "Please input the filename that you want to encrypt/decrypt:";
std::cin >> srcFile;
std::cout << "Please input the encrypted/decrypted filename:";
std::cin >> dstFile;
std::cout << (FileConvert(srcFile, dstFile) ? "encrypt/decrtpt succeed!" : "encrypt/decrypt failed!") << std::endl;
system("pause");
return 0;
}