把以前写过的几个小算法稍整理下子。

1.多表替代密码:

 1 #include<iostream> 
 2 #include<cstdlib>
 3 #include<cstdio>
 4 #include<string>
 5 using namespace std;
 6 
 7 int gcd(int a,int b);          //求最大公约数;
 8 void jiam(string words,int* A);//加密;
 9 void jiem(string words,int* A);//解密。
10 int main()
11 {
12     int A[9],i,tmp;
13     string words;
14     bool r;
15     cout<<"请随意输入一个整数,来改变随机种子:";
16     cin>>i;
17     srand(i);
18     getchar();
19     cout<<"系统随机生成一个三阶矩阵:"<<endl;
20     t:
21     for(i=0;i<9;i++)
22     {
23         A[i]=rand()%26;
24     }
25     tmp=A[0]*(A[4]*A[8]-A[5]*A[7])-A[1]*(A[3]*A[8]-A[5]*A[6])+A[2]*(A[3]*A[7]-A[4]*A[6]);
26     if(gcd(tmp,26)!=1)
27     goto t;
28     for(i=0;i<9;i++)
29     {
30         if(i==2||i==5||i==8)
31         cout<<A[i]<<";"<<endl;
32         else
33         cout<<A[i]<<"   ";
34     }
35     cout<<endl;
36     cout<<"请输入明文或密文(大写):";
37     getline(cin,words);
38     cout<<"加密(0)?解密(1)?请输入 0 or 1:";
39     cin>>r;
40     if(r==0)
41     jiam(words,A);
42     else
43     jiem(words,A);
44     return 0;
45 }
46 void jiam(string words,int* A)
47 {
48     int i;
49     for(i=0;i<words.length();i+=3)
50     {
51         cout<<char((A[0]*(int(words[i])-65)+A[1]*(int(words[i+1])-65)+A[2]*(int(words[i+2])-65))%26+65);
52         cout<<char((A[3]*(int(words[i])-65)+A[4]*(int(words[i+1])-65)+A[5]*(int(words[i+2])-65))%26+65);
53         cout<<char((A[6]*(int(words[i])-65)+A[7]*(int(words[i+1])-65)+A[8]*(int(words[i+2])-65))%26+65);
54     }
55     cout<<endl;
56 }
57 void jiem(string words,int* A)
58 {
59     int i,x,y,z;
60     for(i=0;i<words.length();i+=3)
61     {
62         for(x=0;x<26;x++)
63         for(y=0;y<26;y++)
64         for(z=0;z<26;z++)
65         {
66             if(char((A[0]*x+A[1]*y+A[2]*z)%26+65)==words[i]&&char((A[3]*x+A[4]*y+A[5]*z)%26+65)==words[i+1]&&char((A[6]*x+A[7]*y+A[8]*z)%26+65)==words[i+2])
67             goto xx;
68         }
69         xx:
70         cout<<char(x+65)<<char(y+65)<<char(z+65);
71     }
72     cout<<endl;
73 }
74 int gcd(int a,int b)
75 {
76     if(b==0)
77        return a;
78     else
79        return gcd(b,a%b);
80 }
View Code

相关文章:

  • 2021-08-24
  • 2021-06-02
  • 2022-01-12
  • 2021-12-09
  • 2021-08-01
  • 2022-12-23
  • 2021-09-20
  • 2022-12-23
猜你喜欢
  • 2021-08-11
  • 2022-01-27
  • 2021-10-28
  • 2022-12-23
  • 2022-02-19
  • 2022-01-22
  • 2021-06-04
相关资源
相似解决方案