南邮密码学实验:转轮密码机
题目
现代密码学教程第2版[谷利泽,郑世慧,杨义先编著]2015年版
3.2.3(P53~55)
解释
输入一个字母
根据对应的慢轮子、中轮子、快轮子的对应的变换,
输出另一个字母
每输入一个,慢轮子下转一格,
慢轮子转一圈之后,中轮子下转一格,
中轮子下转一圈,快轮子下转一格
想法
1、对于这个轮子来说,他的属性是固定的,也就是输入、输出,行为也是固定的,就左右数字匹配、旋转
所以觉得用面向对象方便些
这题面向编程的写法我朋友写了,看上去有点麻烦:
2、然后我稍微加了点,确保稳定性:若读取小写字母,变为大写字母,若读取非字母,直接输出
3、当然这题用Python应该更好写一点,不过C++都写出来了,Python重构下应该也不费事(
代码(C++)
#include<iostream>
#include<cstring>
#define N 100005
using namespace std;
class Wheel //定义轮子类
{
private:
int left[26]; //左侧数字
int right[26]; //右侧数字
int time; //轮子转数
public:
void Set(int *l,int *r,int time); //设置函数
void Read(int i); //读取函数
int Roll(); //轮子旋转函数
int Match(int x); //轮子数字匹配函数
};
void Wheel::Set(int *l,int *r,int time=0)
{
for(int i=0;i<26;i++)
{
left[i]=l[i];
right[i]=r[i];
}
}
void Wheel::Read(int i)
{
cout<<left[i]<<'\t'<<right[i]<<'\t'<<'\t';
}
int Wheel::Roll()
{
int templ=left[25],tempr=right[25];
for(int i=24;i>=0;i--)
left[i+1]=left[i],right[i+1]=right[i];
left[0]=templ;right[0]=tempr;
time++;
if(time==26)
{
time=0;
return 1;
}
return 0;
}
int Wheel::Match(int x)
{
for(int i=0;i<26;i++)
{
if(right[i]==left[x])
return i;
}
}
class wheelMachine //定义密码机类
{
private:
Wheel Slow; //慢轮子
Wheel Middle; //中轮子
Wheel Fast; //快轮子
public:
void Reset(); //重置函数
void Read(); //读取函数
char Code(char x); //加密函数
void Roll(); //旋转函数
void Use(char *s); //使用函数
};
void wheelMachine::Reset()
{
char IO[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int sl[26]={24,25,26,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
int sr[26]={21,3,15,1,19,10,14,26,20,8,16,7,22,4,11,5,17,9,12,23,18,2,25,6,24,13};
int ml[26]={26,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
int mr[26]={20,1,6,4,15,3,14,12,23,5,16,2,22,19,11,18,25,24,13,7,10,8,21,9,26,17};
int fl[26]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
int fr[26]={8,18,26,17,20,22,10,3,13,11,4,23,5,24,9,12,25,16,19,6,15,21,2,7,1,14};
Slow.Set(sl,sr);
Middle.Set(ml,mr);
Fast.Set(fl,fr);
}
void wheelMachine::Read()
{
cout<<' '<<"慢轮子"<<" \t\t"<<"中轮子"<<" \t\t\t"<<"快轮子"<<endl;
for(int i=0;i<26;i++)
{
Slow.Read(i),
Middle.Read(i),
Fast.Read(i),
cout<<endl;
}
}
char wheelMachine::Code(char x)
{
cout<<char(Fast.Match(Middle.Match(Slow.Match(int(x)-65)))+65);
Roll();
}
void wheelMachine::Roll()
{
if(Fast.Roll()==1)
if(Middle.Roll()==1)
Slow.Roll();
}
void wheelMachine::Use(char *s)
{
for(int i=0;i<strlen(s);i++)
{
if(s[i]>='a' && s[i]<='z')
Code(char(s[i]+'A'-'a'));
else if(s[i]>='A' && s[i]<='Z')
Code(s[i]);
else
cout<<s[i];
}
cout<<endl;
}
int main()
{
wheelMachine Machine;
Machine.Reset();
Machine.Read();
char *s="Hello World!";
Machine.Use(s);
Machine.Read();
return 0;
}