Affine 암호에서 알파벳의 각 문자는 해당 숫자로 매핑되며 단일 알파벳 대체 암호의 한 유형입니다. 암호화는 간단한 수학 함수를 사용하여 수행되고 다시 문자로 변환됩니다.
m 크기의 알파벳 문자는 먼저 Affine 암호에서 0 ... m-1 범위의 정수에 매핑됩니다.
Affine 암호의 '키'는 a와 b의 2개의 숫자로 구성됩니다. 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