编程实现恩格玛加密机(C++)

相信各位看了《模仿游戏》之后,都会对这个二战的加密方法感到很好奇吧,我也不例外,因此编了个程序实现了恩格玛加密机,这机器最大的特点就是有着自反性,只要初始设置一致的时候,那么它就是自反的,比如输入A,加密后B,在一样的设置下,输入B一定会输出A。
详细的介绍可以看这里:
http://www.zhihu.com/question/28397034

下面我实现的是简化版的,没有插线板(如果加上去也是很简单的,只需要替换指定的字母就可以了,这里为了简洁就不添加了)

#include <string>
#include <iostream>
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;
}
  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值