使用C++写一个简单的希尔加密和解密
时间: 2023-08-11 12:05:01 浏览: 74
好的,以下是一个简单的希尔加密和解密的 C++ 代码示例:
```c++
#include <iostream>
#include <string>
using namespace std;
string encrypt(string plaintext, int key) {
string ciphertext = "";
for (int i = 0; i < plaintext.length(); i++) {
char c = plaintext[i];
if (isalpha(c)) {
c = tolower(c);
c = (c - 'a' + key) % 26 + 'a';
}
ciphertext += c;
}
return ciphertext;
}
string decrypt(string ciphertext, int key) {
string plaintext = "";
for (int i = 0; i < ciphertext.length(); i++) {
char c = ciphertext[i];
if (isalpha(c)) {
c = tolower(c);
c = (c - 'a' - key + 26) % 26 + 'a';
}
plaintext += c;
}
return plaintext;
}
int main() {
string plaintext = "hello world";
int key = 3;
string ciphertext = encrypt(plaintext, key);
cout << "Ciphertext: " << ciphertext << endl;
string decrypted_text = decrypt(ciphertext, key);
cout << "Decrypted text: " << decrypted_text << endl;
return 0;
}
```
以上代码中,`encrypt()` 函数接受一个明文和一个密钥,返回加密后的密文;`decrypt()` 函数接受一个密文和一个密钥,返回解密后的明文。在加密和解密时,只对字母进行加密和解密操作,其他字符不变。