C++ 使用異或對字符串進行簡單加密

在很多場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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章