對映密碼的加密,解密以及暴力破解
阿新 • • 發佈:2018-11-20
演算法描述:資料按照線性函式加密
y = (a*x+b) mod m (gcd(a,m)=1)
解密
x = (y-b)*af mond m (gcd(af,m)=1, af和a互逆)
暴力破解
列舉a, b,其中a, b範圍是[1,m-1]
C/C++語言程式碼
加密函式
void Encrypt(char *txt, int a, int b) { int len = lstrlenA(txt); for (int i = 0; i < len; i++) txt[i] = (a*txt[i] + b) % 0x7F; }
解密函式
int gcd(int m, int n) { int r, t; if (m < n) { t = m; m = n; n = t; } while ((r = m % n) != 0) { m = n; n = r; } return n; } void Decrypt(char *txt, int a, int b) {//b位移[1,0x7E],有意義 int len = lstrlenA(txt), af = 2, x; while (true) { if (af*a % 0x7F == 1 && gcd(af, 0x7F) == 1) break; af++;//取得a逆 } for (int i = 0; i < len; i++) { x = txt[i] - b; txt[i] = (x >= 0 ? x : x + 0x7F)*af % 0x7F; } }
暴力破解函式
void Crack(char *txt) { int len = lstrlenA(txt) + 1, a, b; char *tmp = new char[len]; for (a = 1; a < 0x7F; a++) { if (gcd(a, 0x7F) == 1) {//存在a逆 for (b = 1; b < 0x7F; b++) { memcpy(tmp, txt, len); Decrypt(tmp, a, b); std::cout << "Cracked at a=" << a << ",b=" << b << ": " << tmp << std::endl; } } } delete[] tmp; }
Main函式
int main(){ char szText[200]; std::cout << "Enter text: "; std::cin.getline(szText, 200); Encrypt(szText, 9, 13); std::cout << "Encrypt text: " << szText << std::endl; Crack(szText); Decrypt(szText, 9, 13); std::cout << "Decrypt text: " << szText << std::endl; }
測試結果圖: