算法描述:数据按照线性函数加密
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; }
测试结果图: