用于实现仿射密码的C ++程序
在“仿射”密码中,字母表中的每个字母都映射到其等效的数字,是一种单字母替换密码。使用简单的数学函数完成加密,然后将其转换回字母。
在仿射密码中,大小为m的字母首先映射到0…m-1范围内的整数,
仿射密码的“键”由2个数字a和b组成。a应该选择为相对于m素数。
加密
为了转换整数,它使用了模块化算法,即每个明文字母对应于另一个与密文字母对应的整数。单个字母的加密功能是
E ( x ) = ( a x + b ) mod mmodulus m: size of the alphabet
a and b: key of the cipher.
解密
在解密中,将每个密文字母转换为它们的整数值。解密功能是
D ( x ) = a^-1 ( x - b ) mod ma^-1 : modular multiplicative inverse of a modulo m. i.e., it satisfies the equation
1 = a^-1 mod m.
这是一个实现该过程的C ++程序。
演算法
BeginFunction encryption(string m)
for i = 0 to m.length()-1
if(m[i]!=' ')
c = c + (char) ((((a * (m[i]-'A') ) + b) % 26) + 'A')
else
c += m[i]
return c
End
Begin
Function decryption(string c)
Initialize a_inverse = 0
Initialize flag = 0
For i = 0 to 25
flag = (a * i) % 26
if (flag == 1)
a_inverse = i
done
done
For i = 0 to c.length() - 1
if(c[i]!=' ')
m = m + (char) (((a_inverse * ((c[i]+'A' - b)) % 26)) + 'A')
else
m = m+ c[i]
done
End
示例
#include<bits/stdc++.h>using namespace std;
static int a = 7;
static int b = 6;
string encryption(string m) {
//Cipher Text initially empty
string c = "";
for (int i = 0; i < m.length(); i++) {
// Avoid space to be encrypted
if(m[i]!=' ')
// added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
c = c + (char) ((((a * (m[i]-'A') ) + b) % 26) + 'A');
else
//else append space character
c += m[i];
}
return c;
}
string decryption(string c) {
string m = "";
int a_inverse = 0;
int flag = 0;
//Find a^-1 (the multiplicative inverse of a
//in the group of integers modulo m.)
for (int i = 0; i < 26; i++) {
flag = (a * i) % 26;
//Check if (a * i) % 26 == 1,
//then i will be the multiplicative inverse of a
if (flag == 1) {
a_inverse = i;
}
}
for (int i = 0; i < c.length(); i++) {
if(c[i] != ' ')
// added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
m = m + (char) (((a_inverse * ((c[i]+'A' - b)) % 26)) + 'A');
else
//else append space character
m += c[i];
}
return m;
}
int main(void) {
string msg = "nhooo";
string c = encryption(msg);
cout << "Encrypted Message is : " << c<<endl;
cout << "Decrypted Message is: " << decryption(c);
return 0;
}
输出结果
Encrypted Message is : JQJAVKGFCHAKTJDecrypted Message is: nhooo
以上是 用于实现仿射密码的C ++程序 的全部内容, 来源链接: utcz.com/z/322489.html