当前位置: 移动技术网 > IT编程>开发语言>C/C++ > Caesar密码

Caesar密码

2018年04月03日  | 移动技术网IT编程  | 我要评论

红豆爱阿翁吧,异世之火德星君txt,水管工游戏

原理:Caesar采用循环移位对明文进行加密。

加密:通过循环移位对明文进行加密。

密钥:1-25之间的任意整数。

比如:明文ABCD

通过密钥1加密后的密文为BCDE;

通过密钥2加密后的密文为CDEF;

通过密钥3加密后的密文为DEFG;

通过密钥4加密后的密文为EFGH;

通过密钥5加密后的密文为FGHI;

通过密钥6加密后的密文为HIJK;

通过密钥7加密后的密文为IJKL;

……

以此类推。

解密:加密的逆运算,通过暴力攻击的方法对密文进行解密,尝试25个密钥,可以得到25种密文,由于需要判断解密之后的明文是否正确,需要对此结果进行分析,通过导入.txt字典文件,将词库中的单词与之比对,如果词库中存在该单词,则很大程度说明此次解密成功,此次解密对应的密钥为正确密钥。

查字典:25次解密,在每次解密过程当中,都在词库中查询解密出来的第一个单词,如果存在,就输出“解密成功”,反之亦然。

算法流程:

 

代码实现:(.txt文件自行导入

 1 #include<iostream>
 2 #include<fstream>
 3 #include<sstream>
 4 #include<string>
 5 #include<map>
 6 #include<vector>
 7 using namespace std;
 8 
 9 //加密
10 void encrypt(string &message, int key)
11 {
12     char ch = '\0';
13     for (unsigned int i = 0; i < message.length(); i++)
14     {
15         if (message[i] >= 'a'&&message[i] <= 'z'){
16             ch = 'a';
17         }
18         else if (message[i] >= 'A'&&message[i] <= 'Z') {
19             ch = 'A';
20         }
21         if (message[i] >= 'A'&&message[i] <= 'Z' || message[i] >= 'a'&&message[i] <= 'z')
22         {
23             message[i] = ch + (message[i] - ch + key) % 26;
24         }
25     }
26 }
27 
28 //解密
29 void decrypt(string &message, int key)
30 {
31     char ch = '\0';
32     for (unsigned int i = 0; i < message.length(); i++)
33     {
34         if (message[i] >= 'a'&&message[i] <= 'z'){
35             ch = 'a';
36         }
37         else if (message[i] >= 'A'&&message[i] <= 'Z'){
38             ch = 'A';
39         }
40         if (message[i] >= 'A'&&message[i] <= 'Z' || message[i] >= 'a'&&message[i] <= 'z')
41         {
42             message[i] = ch + (message[i] - ch + 26 - key) % 26;
43         }
44     }
45 }
46 
47 
48 int main()
49 {
50     string message = "";
51     cout << "请输入明文:" << endl;
52     getline(cin, message, '\n');
53     int key = 0;
54     cout << "请输入密钥key(1-25):" << endl;
55     cin >> key;
56     encrypt(message, key);
57     cout << "加密后的密文为:" << message << endl;
58 
59 
60     ifstream infile("C:\\Users\\yinyin\\Desktop\\Caesar\\caesar\\dictionary.txt", ios::in);
61     if (!infile)
62     {
63         cerr << "open file error!" << endl;
64         return 0;
65     }
66     vector<string> v;
67     bool isFind = false;
68 
69     for (int i = 1; i <= 25; i++)
70     {
71         decrypt(message, 1);
72         cout << "第" << i << "次解密:" << message << endl;
73 
74         bool isFind = false;
75         string word;
76 
77         while (infile >> word)     //读入单词至word
78         {
79             if (message == word)
80             {
81                 isFind = true;
82                 cout << "第" << i << "次解密成功, 明文为:" << message << endl;
83             }
84         }
85     }
86     if (isFind == false)
87     {
88         cout << "查找失败,解密失败!!!";
89     }
90 
91     return 0;
92 }

 运行结果:

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网