仿射变换

/**********************
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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值