/*利用异或运算符 ^(Xor)实现简单信息(string)的加解密*/
/*由于在计算机中数据都是以二进制数进行表示的,如字符串(string)中的各种
字符是采用不同的编码方式(如ASCII或Unicode等)将其用数字表示进行储存的,
且我们注意到对于任意给定的二进制数和给定的key,满足如下等式
0 ^ 1 ^ 1 = 0 1 ^ 1 ^ 1 = 1
0 ^ 0 ^ 0 = 0 1 ^ 0 ^ 0 = 1
即对于任意给定的密钥key来说,每位二进制数与相应的二进制位进行异或两次后
均得到原数据。因此我们可以通过对原数据进行一次异或 ^(Xor)运算得到加密信息,
再进行一次异或运算进行解密并得到明文信息,这不失为一种简单且在某些情况下比较有效的方法
*/
#include <iostream>
#include <string>
using namespace std;
int main() {
string toEncrypt = "We will arrive tonight, keep secure!";
//根据测试,当选择小写字母作为密钥key时,加密得到的信息中
//各字符基本都出现在ASCII码0~32之间,为不可打印字符
char keyToEncrypt = 'K';
/*
char original = 'f'; //当我们知道原文中一个字符及密文中一个相应字符时,
char key = 's'; //我们可以采取如下方法得到密钥key,从而进行解密
char end; //因此此种加密方法(采取单字符密钥)安全性并不是很高
char getKey;
end = original ^ key; //eg:
getKey = original ^ end; //original(1101) ^ key(1011) = end(0110);
cout << getKey << endl; //original(1101) ^ end(0110) = original(1101) ^ (original(1101) ^ key(1011))(0110) = key(1011)
*/
for (int i = 0; i < toEncrypt.size(); i++) {
toEncrypt[i] ^= keyToEncrypt;
}
cout << "The encrypted date = " << toEncrypt << endl;
for (int i = 0; i < toEncrypt.size(); i++) {
toEncrypt[i] ^= keyToEncrypt;
}
cout << "The unencrypted date = " << toEncrypt << endl;
//下面为一种改进的方法
/*
string original = "super flying monkeys are aweseome, aren't they?";
cout << "Original data = " << original << endl;
string encrypted = "";
string unencrypted = "";
char key = 'F';
for (int temp = 0; temp < original.size(); temp++) {
encrypted += original[temp] ^ (int(key) + temp) % 255;
}
cout << "Encrypted data = " << encrypted << endl;
for (int temp = 0; temp < original.size(); temp++) {
unencrypted += encrypted[temp] ^ (int(key) + temp) % 255;
}
cout << "Unencrypted data = " << unencrypted << endl;;
*/
return 0;
}