凯撒密码加解密C++
时间: 2024-04-14 18:22:59 浏览: 219
凯撒密码是一种简单的替换密码,它通过将明文中的每个字母按照一定的偏移量进行替换来实现加密和解密。在C++中,可以使用字符的ASCII码值来进行偏移和替换操作。
下面是一个简单的凯撒密码加解密的C++代码示例:
```cpp
#include <iostream>
using namespace std;
// 凯撒密码加密函数
string caesarEncrypt(string plaintext, int shift) {
string ciphertext = "";
for (int i = 0; i < plaintext.length(); i++) {
// 对字母进行偏移
if (isalpha(plaintext[i])) {
char shiftedChar = (toupper(plaintext[i]) - 'A' + shift) % 26 + 'A';
ciphertext += shiftedChar;
}
else {
ciphertext += plaintext[i];
}
}
return ciphertext;
}
// 凯撒密码解密函数
string caesarDecrypt(string ciphertext, int shift) {
string plaintext = "";
for (int i = 0; i < ciphertext.length(); i++) {
// 对字母进行逆向偏移
if (isalpha(ciphertext[i])) {
char shiftedChar = (toupper(ciphertext[i]) - 'A' - shift + 26) % 26 + 'A';
plaintext += shiftedChar;
}
else {
plaintext += ciphertext[i];
}
}
return plaintext;
}
int main() {
string plaintext = "HELLO WORLD";
int shift = 3;
// 加密
string ciphertext = caesarEncrypt(plaintext, shift);
cout << "加密后的密文:" << ciphertext << endl;
// 解密
string decryptedText = caesarDecrypt(ciphertext, shift);
cout << "解密后的明文:" << decryptedText << endl;
return 0;
}
```
这段代码中,`caesarEncrypt`函数用于加密明文,`caesarDecrypt`函数用于解密密文。其中,`shift`参数表示偏移量,可以是任意整数。在加密时,将明文中的每个字母按照偏移量进行替换;在解密时,将密文中的每个字母按照逆向偏移量进行替换。
阅读全文
相关推荐
















