在很多場C++需要對字符串數據進行加密,可以增加一定的安全係數,例如在網絡傳輸的時候,防止抓包可以看到明文內容。
爲此做了一個使用異或做了簡單的加密方法,記錄一下,代碼如下:
#include <string>
#include <iostream>
using namespace std;
int key[] = { 1,2,3,4,5,6,7};
void encryption(string& c, int key[]) {
int len = c.size();
for (int i = 0; i < len; i++) {
c[i] = c[i] ^ key[i % 7];
}
}
void decode(string& c, int key[]) {
int len = c.size();
for (int i = 0; i < len; i++) {
c[i] = c[i] ^ key[i % 7];
}
}
int main(int argc, char* argv[]) {
std::string str = "hello world!";
std::cout << "原文:" << str << std::endl;
encryption(str, key);
std::cout << "加密後密文:" << str << std::endl;
decode(str, key);
std::cout << "解密後密文:" << str << std::endl;
return 0;
}