实现仿射密码的 C++ 程序
在仿射密码中,字母中的每个字母都映射到其数字等价物,这是一种单字母替换密码。使用简单的数学函数进行加密并转换回字母。
在仿射密码中,首先将大小为 m 的字母映射到 0 ... m-1 范围内的整数,
仿射密码的“密钥”由 2 个数字 a 和 b 组成。应选择 a 与 m 互为素数。
加密
若要转换整数,它使用模运算,其中每个明文对应于另一个对应于密文的一个整数。单个字母的加密函数为
E ( x ) = ( a x + b ) mod m modulus m: size of the alphabet a and b: key of the cipher.
解密
在解密中,将每个密文转换为其整数值。解密函数为
D ( x ) = a^-1 ( x - b ) mod m a^-1 : modular multiplicative inverse of a modulo m. i.e., it satisfies the equation 1 = a^-1 mod m.
以下是一个 C++ 程序来实现此过程。
算法
Begin Function 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 = "TUTORIALSPOINT"; string c = encryption(msg); cout << "Encrypted Message is : " << c<<endl; cout << "Decrypted Message is: " << decryption(c); return 0; }
输出
Encrypted Message is : JQJAVKGFCHAKTJ Decrypted Message is: TUTORIALSPOINT
广告