编写函数,对字符串进行加密、解密。加密、解密的密匙为两位数字,加密时轮流使用密匙中的数字对字符进行加法运算,解密时则轮流使用密匙中的数字对字符进行减法运算。例如,待加密的字符串为"China",密匙为2和5,则加密后的密文为"Emksc",解密后还原为"China"。c++ 数组
时间: 2024-02-09 13:13:04 浏览: 28
下面是一个简单的 C++ 函数来加密和解密字符串,使用了数组存储密匙和字符:
```cpp
#include <iostream>
#include <string>
using namespace std;
string encrypt(string message, int key1, int key2) {
string result = "";
int key[] = { key1, key2 };
int i = 0;
for (char c : message) {
result += (char)(c + key[i % 2]);
i++;
}
return result;
}
string decrypt(string message, int key1, int key2) {
string result = "";
int key[] = { key1, key2 };
int i = 0;
for (char c : message) {
result += (char)(c - key[i % 2]);
i++;
}
return result;
}
int main() {
string message = "China";
int key1 = 2;
int key2 = 5;
cout << "Original message: " << message << endl;
string encrypted = encrypt(message, key1, key2);
cout << "Encrypted message: " << encrypted << endl;
string decrypted = decrypt(encrypted, key1, key2);
cout << "Decrypted message: " << decrypted << endl;
return 0;
}
```
这个程序输出:
```
Original message: China
Encrypted message: Emksc
Decrypted message: China
```
注意,在加密和解密时,使用的密匙是轮流使用的,因此需要使用取模运算来实现。
相关推荐
![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)
![](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)