?
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-434299.html
代碼如下:文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-434299.html
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cmath>
#include<stdio.h>
using namespace std;//定義Caesar類
class Caesar {
private:
int key;// 移位密鑰
public:
Caesar(int k) :key(k) {}//構(gòu)造函數(shù)//使用移位密鑰key對(duì)明文字母進(jìn)行加密
string encrypt(string cleartext) {
string ciphertext;//加密后密文
//自行編寫一段代碼,對(duì)明文區(qū)分大小寫進(jìn)行加密,使得最終效果與步驟截圖同
for (int i = 0; i < cleartext.length(); i++)
{
// 對(duì)小寫字母進(jìn)行加密
if (cleartext[i] >= 'a' && cleartext[i] <= 'z')
ciphertext += char((cleartext[i] - 97 + this->key) % 26 + 97);
// 對(duì)大寫字母進(jìn)行加密
else if (cleartext[i] >= 'A' && cleartext[i] <= 'Z')
ciphertext += char((cleartext[i] - 65 + this->key) % 26 + 65);
}
//返回加密后密文
return ciphertext;
}
//使用窮舉法進(jìn)行破譯
vector<string>decrypt(string ciphertext)
{
vector<string>cleartextSet;//定義解密后的明文信息
//解密公式:
//f(a) = (a + (26 - N)) mod 26//自行編寫一段代碼,窮舉26個(gè)密鑰對(duì)密文區(qū)分大 小寫進(jìn)行解密以此判斷 明文,使得最終效果與步驟截圖同
// 密鑰為0時(shí),明密文完全相同,直接將密文串進(jìn)行保存
cleartextSet.push_back(ciphertext);
// 將其余25個(gè)不同的密鑰進(jìn)行窮舉及解密
for (int i = 1; i < 26; i++)
{
// 用一個(gè)臨時(shí)變量對(duì)解密的后的字符串進(jìn)行保存
string s;
for (int j = 0; j < ciphertext.length(); j++)
{
//對(duì)密文串中的小寫字母進(jìn)行解密
if (ciphertext[j] >= 'a' && ciphertext[j] <= 'z')
s += char((ciphertext[j] - 97 +26-i) % 26 + 97);
//對(duì)密文串中的大寫字母進(jìn)行解密
else if (ciphertext[j] >= 'A' && ciphertext[j] <= 'Z')
s += char((ciphertext[j] - 65 +26 - i) % 26 + 65);
}
//將字符串傳入到容器中進(jìn)行保存
cleartextSet.push_back(s);
}
return cleartextSet;
}
};
int main()
{
int mode, flag = 1;
while (flag)
{
cout << "---------- Caesar加解密!----------" << endl;
cout << "請(qǐng)選擇[1->encrypt 2->decrypt 3->exit]" << endl;
cin >> mode;
if (mode != 1 && mode != 2 && mode != 3)
{
cout << "輸入錯(cuò)誤,請(qǐng)重輸 :[1->encrypt 2->decrypt 3->exit]" << endl;
cin >> mode;
}
if (mode == 1)
{
int myKey;
cout << "輸入移位密鑰: ";
cin >> myKey;//輸入移位密鑰
Caesar myCaesar(myKey);
string cleartext;//待加密的明文
string ciphertext;//加密后的密文
cout << "輸入要加密的明文: " << endl;
getchar();
getline(cin, cleartext);
ciphertext = myCaesar.encrypt(cleartext);
cout << "加密后的密文: " << endl;
cout << ciphertext << endl;
}
else if (mode == 2) {
vector<string>textset;//用于存放明文
string ciphertext;//待解密的密文
Caesar myCaesar(0);
cout << "輸入要解密的密文: " << endl;
getchar();
getline(cin, ciphertext);
textset = myCaesar.decrypt(ciphertext);
int k;
for (k = 0; k < textset.size(); k++) {
cout << "If (key mod 26) == " << k << ": " << endl;
cout << textset[k] << endl;
}
}
else {
return 0;
}
cout << "是否繼續(xù)加解密? [0->exit 1 or other->continue]: ";
cin >> flag;
}
return 0;
}
到了這里,關(guān)于凱撒密碼——密碼學(xué)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!