用CPP实现异或加密解密
时间: 2024-05-15 07:12:33 浏览: 15
异或加密是一种简单的加密方式,可以使用CPP语言实现。
加密和解密过程都是通过将明文与密钥进行异或操作来实现的,具体步骤如下:
加密:将明文的每一个字节与密钥的对应字节进行异或操作,得到密文。
解密:将密文的每一个字节与密钥的对应字节进行异或操作,得到明文。
下面是一个简单的CPP函数,实现异或加密解密的功能:
```cpp
#include <iostream>
#include <string>
using namespace std;
string encryptDecrypt(string str, char key)
{
string result = str;
for (int i = 0; i < str.size(); i++)
{
result[i] = str[i] ^ key;
}
return result;
}
int main()
{
string plaintext = "Hello, world!";
char key = 'a';
string ciphertext = encryptDecrypt(plaintext, key);
cout << "Plaintext: " << plaintext << endl;
cout << "Key: " << key << endl;
cout << "Ciphertext: " << ciphertext << endl;
string decryptedtext = encryptDecrypt(ciphertext, key);
cout << "Decryptedtext: " << decryptedtext << endl;
return 0;
}
```
运行结果如下:
```
Plaintext: Hello, world!
Key: a
Ciphertext: Ge]]b#*#b`c[#
Decryptedtext: Hello, world!
```
注意,此方法并不是一种强加密算法,只适合于简单的加密应用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)