c++凯撒加密的破解代码
时间: 2023-10-28 16:57:17 浏览: 184
凯撒加密程序 C++编写
4星 · 用户满意度95%
凯撒加密是一种很古老的加密算法,容易被破解。以下是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++) {
if (isalpha(plaintext[i])) {
char c = plaintext[i];
if (isupper(c)) {
c = (c + key - 65) % 26 + 65;
}
else {
c = (c + key - 97) % 26 + 97;
}
ciphertext += c;
}
else {
ciphertext += plaintext[i];
}
}
return ciphertext;
}
// 凯撒解密
string decrypt(string ciphertext, int key) {
string plaintext = "";
for (int i = 0; i < ciphertext.length(); i++) {
if (isalpha(ciphertext[i])) {
char c = ciphertext[i];
if (isupper(c)) {
c = (c - key - 65 + 26) % 26 + 65;
}
else {
c = (c - key - 97 + 26) % 26 + 97;
}
plaintext += c;
}
else {
plaintext += ciphertext[i];
}
}
return plaintext;
}
// 破解凯撒加密
string decrypt_caesar(string ciphertext) {
string plaintext = "";
for (int key = 0; key < 26; key++) {
plaintext = decrypt(ciphertext, key);
cout << "key = " << key << " plaintext = " << plaintext << endl;
}
return plaintext;
}
int main() {
string ciphertext = "Khoor, zruog!";
string plaintext = decrypt_caesar(ciphertext);
return 0;
}
```
以上代码演示了如何对凯撒加密进行破解。假设我们已知密文是“Khoor, zruog!”,我们可以通过枚举所有可能的密钥(0-25)来尝试解密。最终,我们找到了正确的密钥(3),并成功地解密了原始文本(Hello, world!)。
阅读全文