相信各位看了《模仿游戏》之后,都会对这个二战的加密方法感到很好奇吧,我也不例外,因此编了个程序实现了恩格玛加密机,这机器最大的特点就是有着自反性,只要初始设置一致的时候,那么它就是自反的,比如输入A,加密后B,在一样的设置下,输入B一定会输出A。
?
下面我实现的是简化版的,没有插线板(如果加上去也是很简单的,只需要替换指定的字母就可以了,这里为了简洁就不添加了)
#include
#include
using namespace std; string Enigma(string input){ int code; int n[6] = {24,2,5,4,10,23}; //定义6个转子 int nsize=6; string output; for (int i = 0; i < input.size();i++) { if(input[i]==' '){output+=' ';continue;} code = input[i]-'a'; for (int j = 0; j < nsize;j++) { code = (code + n[j]) % 26; } if(code%2==0) code++;else code--; //反射器如果偶数+1,奇数-1,反射器只要能实现字母两两配对就可以了。 for (int j = nsize-1; j >=0;j--) { code = code - n[j]; if(code<0)code=26+code; } n[0]++; for (int j = 0; j < nsize-1; j++) { if (n[j]>=26) { n[j + 1]++; n[j] = 0; } } n[nsize-1] = n[nsize-1] % 26; output += code+'a'; } return output; } int main() { string text=hey hey helloworld; string miwen=Enigma(text); cout <<密文:<< miwen<< endl; cout <<明文:<< Enigma(miwen) << endl; return 0; }