仿射密码及c++实现

仿射函数(affine)

所谓仿射函数,是指满足如下条件的函数

在域中,有函数映射,c=ax+b,其中a有逆元,也就是x有唯一解。

一般来说,仿射函数定义在有限的数域中。古典密码的仿射函数是

c = (ax+b) mod 26, 一般只考虑26个英文字母,其中a满足与26互素。

显然,只有a与26互素,根据贝祖定理,有

sa+26t = 1

则有

sc = (sax+sb) mod 26
sc = (x+sb) mod 26
x= (sc-sb) mod 26

之所以要让x是唯一的,只是为了让解密唯一,不会产生歧义。
故在仿射密码中,加密函数为

c = (ax+b) mod 26, c为密文,x为明文,a、b为参数,满足gcd(a,26)=1

解密函数为

x = (sc-sb) mod 26, 其中有 sa = 1 mod 26

有时候,为了方便,可以设b为0。然而,这样做会让密钥空间得很小。因为与26互素的只有12个。
为了求出s,可能需要扩展的欧几里得算法,但是,由于这里的数字较小,完全可以用暴力搜索,求出s。

c++语言实现

#include<iostream>
using namespace std;
int find_s(int a){
	for(int i=1;i<26;i++){
		if(a*i%26==1){
			return i;
		}
	}
}
string encrypt(int a,int b,string message){
	for(int i=0;i<message.size();i++){
		message[i]-='a';
		message[i]=(a*message[i]+b)%26;
		message[i]+='A';
	}
	return message;
}
string decrypt(int a,int b,string cipher){
	int s=find_s(a);
	for(int i=0;i<cipher.size();i++){
		cipher[i]-='A';
		cipher[i]=(s*cipher[i]+(26-s)*b)%26;//adding 26-s equals -s.
		cipher[i]+='a';
	}
	return cipher;
}
int main(){
	int a=3,b=7;//the key
	string m;
	cout<<"Please enter the message:"<<endl;
	cin>>m;
	string c;
	c=encrypt(a,b,m);
	cout<<"The ciphertext is "<<c<<endl;;
	m=decrypt(a,b,c);
	cout<<"After decryption "<<m<<endl;
}
仿射密码是一种简单的替换加密算法,在C++实现加解密的过程如下: **加密过程**: 1. 定义两个整数a和b作为密钥,通常它们满足(a * b) % 26 = 1(因为字母表只有26个字符)。例如,a=5, b=7。 2. 将明文(每个字母表示为ASCII码减去'A'或'a'的值,范围为0-25)乘以a,然后加上b,结果对26取模,得到密文的ASCII码。 3. 转换回字母形式,如果超出A-Z或a-z的范围,则循环回到开始。 **解密过程**: 1. 使用同样的a和b,将密文的ASCII码减去b,然后除以a并取余数,得到的余数对应明文字母的原始位置。 2. 再次转换回字母形式。 以下是简单的C++代码示例: ```cpp #include <iostream> using namespace std; char encryptAffine(char c, int a, int b) { c = (a * (c - 'A') + b) % 26 + 'A'; return c; } char decryptAffine(char c, int a, int b) { c = (char)(((c - 'A') - b) * (int)a) % 26 + 'A'; return c; } int main() { int a = 5, b = 7; // 示例密钥 string plaintext = "Hello, World!"; string ciphertext; for (char c : plaintext) { if ('A' <= c && c <= 'Z') { // 处理大写字母 ciphertext += encryptAffine(c, a, b); } else if ('a' <= c && c <= 'z') { // 处理小写字母 ciphertext += encryptAffine(c, a, b); } else { ciphertext += c; // 非字母字符不变 } } cout << "Encrypted message: " << ciphertext << endl; for (char c : ciphertext) { if ('A' <= c && c <= 'Z') { cout << decryptAffine(c, a, b) << " "; } else if ('a' <= c && c <= 'z') { cout << decryptAffine(c, a, b) << " "; } else { cout << c << " "; // 非字母字符不变 } } cout << endl << "Decrypted message: "; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值