输入需要加密的信息,随机生成一个字节的二进制代码,与信息进进行异或运算,得到加密后的密文;密文与随机字节进行异或,得到加密前的信息明文。c++实现
时间: 2024-02-12 07:05:25 浏览: 32
以下是一个简单的 C++ 实现:
```cpp
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
string encrypt(string message)
{
srand(time(0)); // 初始化随机数生成器
char key = rand() % 256; // 生成一个随机字节
string ciphertext = message;
// 对每个字符进行异或运算
for (int i = 0; i < message.length(); i++) {
ciphertext[i] = message[i] ^ key;
}
ciphertext = key + ciphertext; // 在密文前加上随机字节
return ciphertext;
}
string decrypt(string ciphertext)
{
char key = ciphertext[0]; // 获取随机字节
string message = ciphertext.substr(1);
// 对每个字符进行异或运算
for (int i = 0; i < message.length(); i++) {
message[i] = message[i] ^ key;
}
return message;
}
int main()
{
string message, ciphertext, decrypted;
cout << "请输入需要加密的消息:";
getline(cin, message);
ciphertext = encrypt(message);
cout << "密文为:" << ciphertext << endl;
decrypted = decrypt(ciphertext);
cout << "解密后的明文为:" << decrypted << endl;
return 0;
}
```
该程序会首先生成一个随机字节作为密钥,然后对输入的消息进行异或运算得到密文。密文的第一个字符是随机字节,后面是加密后的消息。解密时先取出第一个字符作为密钥,对密文后面的字符进行异或运算得到原始消息。
相关推荐
![hpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)