/**********************
c=E[a,b](m)=am+b(mod 26)
m=D[a,b](c)=a^(-1)(c-b)(mod 26)
0<=a,b<=25;gcd(a,26)=1
支持大小写英文字母
**********************/
#include <bits/stdc++.h>
using namespace std;
//模重复平方运算
int qe2(int x, int y, int m)
{
int a = 1, b = x, n = y;
while(n){
if(n&1)
a = (a*b) % m;
b = (b*b) % m;
n>>=1;
}
return a;
}
int SovleInverse(int a)
{
return qe2(a, 11, 26);
}
string Encryption(string m, int a, int b)
{
int len = m.length();
string c = m;
for(int i=0; i<len; ++i){
if(c[i] >= 'a' && c[i] <= 'z')
c[i] = ((a * (int)(m[i] - 'a') + b) % 26) + 'a';
if(c[i] >= 'A' && c[i] <= 'Z')
c[i] = ((a * (int)(m[i] - 'A') + b) % 26) + 'A';
}
return c;
}
string Decryption(string c, int a, int b)
{
int len = c.length();
string m = c;
int a_n = SovleInverse(a);
for(int i=0; i<len; ++i){
if(c[i] >= 'a' && c[i] <= 'z')
m[i] = (a_n * ((int)(c[i] - 'a' + 26) - b) % 26) + 'a';
if(c[i] >= 'A' && c[i] <= 'Z')
m[i] = (a_n * ((int)(c[i] - 'A' + 26) - b) % 26) + 'A';
}
return m;
}
int main()
{
while(1){
int selectnum;
cout << "Encryption (1)? Decryption (2)? Exit (4)" <<endl;
cin >> selectnum;
if(selectnum == 1){
cout << "Please enter plaintext" <<endl;
string m;
cin >> m;
cout << "Please enter the key a,b" <<endl;
int a, b;
cin >> a >> b;
cout << "Ciphertext : " << Encryption(m, a, b) <<endl;
cout << "----------------" <<endl;
}
else if(selectnum == 2){
cout << "Please enter cipher text" <<endl;
string c;
cin >> c;
cout << "Please enter the key a,b" <<endl;
int a, b;
cin >> a >> b;
cout << "Plaintext : " << Decryption(c, a, b) <<endl;
cout << "----------------" <<endl;
}
else
return 0;
}
}
仿射变换
最新推荐文章于 2024-04-26 21:34:12 发布