仿射密码的加密和解密,蛮力攻击C++实现

来源:互联网 发布:网络配线架有什么用 编辑:程序博客网 时间:2024/05/17 05:57

实现代码如下:

void exEuclidean(int a,int b,int &s,int &t){      int r1 = a, r2 = b , s1 = 1, s2 = 0, t1 = 0, t2 = 1;//初始化      int q,r;       while(r2 > 0)      {          q = r1 / r2;            r = r1 - q * r2; //也就是r = r1%r2;          r1 = r2;          r2 = r;            s = s1 - q * s2;          s1 = s2;          s2 = s;                  t = t1 - q * t2;          t1 = t2;          t2 = t;       }      //gcd(a,b) = r1;       s = s1;       t = t1;  }  int findReverse(int a,int n){ //找出a关于n的乘法逆  int s,t;        exEuclidean(n,a,s,t); //因为传引用,s和t得到解了       int a_ = (t >= 0) ? (t % n) : ((t-t*n)%n); //乘法逆就是t映射于n的值       return a_;}string encode(string text,int addKey,int mulKey){string password = "";for(int i = 0 ; i < text.size(); i++){int code = text[i] - 'a';password += (code * mulKey + addKey) % 26 + 'A';}return password;//得到密文 }string decode(string password,int addKey,int mulKey){string text = "";for(int i = 0 ; i < password.size(); i++){int code = password[i] - 'A';text += ( (code - addKey + 26) * findReverse(mulKey,26))% 26 + 'a';}return text;//得到密文 }int main(){ int addKey = 2 ,mulKey = 7;string s;cin>>s;string password = encode(s,addKey,mulKey);printf("得到密文:"); cout<<password<<endl;string text = decode(password,addKey,mulKey);printf("解码得到明文:"); cout<<text<<endl;//假设对于得到的密文进行密钥枚举的破解 printf("接下来演示蛮力攻击:\n"); printf("得到密文:PWUFFOGWCHFDWIWEJOUUNJORSMDWRHVCMWJUPVCCG\n枚举得到的明文如下:\n"); s.clear();s += "PWUFFOGWCHFDWIWEJOUUNJORSMDWRHVCMWJUPVCCG";int mul[12] = {1,3,5,7,9,11,15,17,19,21,23,25} ;//这12个元素有乘法逆 for(int i = 0 ; i < 10 ; i++){//枚举加法密钥 for(int j = 0 ; j < 12; j++){ //枚举乘法密钥 text = decode(s,i,mul[j]);cout<<text<<endl;}}}
对于加法密钥为2,乘法密钥为7的字符串"hello"的加密结果为"ZEBBW"

蛮力攻击的枚举结果如下:

略去了一些无关的枚举结果,那么通过对于26*12种枚举结果,就有可能发现有意义的密文从而找到对应的2个密钥从而实现后续的窃听。

原创粉丝点击