简单替换密码是明文和密文字母使用某种映射以达到加密目的的密码,通常是顺序字母与其一种排列组合映射,其中凯撒密码使用的3位移位密码就是简单替换密码一种,凯撒密码使用的是一种线性函数y=(x+3)%26(比如a->D),这种密码也叫仿射密码。常用的简单替换密码分析是统计字符频率,在一篇文章中,每个字母出现通常具有统计规律,例如e出现的频率最高,利用这一点就能对简单替换密码进行分析,而且密文越多,越符合统计规律,分析的就越准确。
为了简化统计步骤,博主编写了一个程序用以统计密文中各字母出现的频率,并显示与统计规律相适应进行替换的密文。代码如下:
#include<iostream> using namespace std; int main() { int len = 0; cout << "how many space you need?" << endl; cin >> len; char* str = new char[len],*p;//字符串 int a[26] = { 0 }; char c[26]; char stdChar[26] = { 'e','t','a','o','i','n','s','h','r','d','l','c','u','m','w','f','g','p','y','b','v','k','x','j','q','z',}; for (int i = 0; i < 26; i++)c[i] = 'A' + i; cout << "please input a string:" << endl; cin >> str; p = str; while (*p != '\0')a[(*p++)-'A']++; for (int i = 0; i < 26; i++) {//排序 for (int j = i + 1; j < 26; j++) { if (a[i] < a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; char tempc = c[i]; c[i] = c[j]; c[j] = tempc; } } } for (int i = 0; i < 26; i++)cout <<c[i]<< ":" <<a[i] << endl;//输出频率 p = str; while (*p != '\0') {//替换字母 for(int i=0;i<26;i++) if (*p == c[i]) { p++; cout << stdChar[i]; break; } } cout << endl; system("pause"); return 0; }
代码相对简单,没有进行优化。效果如下图所示:
解释一下运行步骤:
- 输入你要输入字母的个数(大于那个数就行了,一般1000应该能应付的了)
- 输入密文(这里密文是大写字母组合,不能有空格和换行)
- 降序显示字母出现的频率以及替换相应字符和的文本。
最后给那些不愿意编译的懒汉提供一份已经编译好的c++可执行程序,提取码: xvjm