[C++]RSA加密加密解密报错!
我最近想做一个RSA加密解密但出现了bug.求大神解答!
程序代码:
#include <iostream> #include <math.h> #include <stdlib.h> #include <string.h> #include <time.h> using namespace std; int gcd(int a, int b) // 求最大公约数 { if (b == 0) return a; else return gcd(b, a % b); } int mod(int a, int b, int n) // 快速模运算 { int c = 0; for (int i = b - 1; i >= 0; i--) { c = 2 * c; if ((n >> i) & 1) { c++; } c = c % n; a = ((long long)a * a) % n; } return c; } char* utf8IntsToString(const int* ints, int len) // 将UTF-8编码的整数数组转换成字符串 { char* str = new char[len + 1]; int j = 0; for (int i = 0; i < len; i++) { if (ints[i] < 0x80) { // ASCII字符 str[j] = (char)ints[i]; j++; } else { // 非ASCII字符,使用UTF-8编码 if (ints[i] < 0x800) { str[j] = (char)((ints[i] >> 6) | 0xC0); str[j + 1] = (char)((ints[i] & 0x3F) | 0x80); j += 2; } else if (ints[i] < 0x10000) { str[j] = (char)((ints[i] >> 12) | 0xE0); str[j + 1] = (char)(((ints[i] >> 6) & 0x3F) | 0x80); str[j + 2] = (char)((ints[i] & 0x3F) | 0x80); j += 3; } else { // 不支持4字节编码 str[j] = '?'; j++; } } } str[j] = '\0'; return str; } int* stringToUtf8Ints(const char* str, int& len); // 转换字符串为UTF-8编码的整数数组 char* utf8IntsToString(const int* ints, int len); // 转换UTF-8编码的整数数组为字符串 int main() { srand((unsigned)time(NULL)); // 生成公私钥对 int p, q, n, fn, e, d; p = 61; // 随机选取两个素数p和q q = 53; n = p * q; fn = (p - 1) * (q - 1); do { e = rand() % (fn - 2) + 2; } while (gcd(e, fn) != 1); for (d = 1; d <= fn; d++) { if (((long long)e * d) % fn == 1) break; } cout << "公钥为 (" << e << ", " << n << ")" << endl; // 输出公私钥 cout << "私钥为 (" << d << ", " << n << ")" << endl; // 加密消息 string msg; cout << "请输入要加密的消息:"; getline(cin, msg); int len; int* M = stringToUtf8Ints(msg.c_str(), len); int* C = new int[len]; for (int i = 0; i < len; i++) { C[i] = mod(M[i], e, n); } cout << "加密结果:"; for (int i = 0; i < len; i++) cout << C[i] << " "; cout << endl; // 解密消息 char* D = utf8IntsToString(C, len); int* M2 = stringToUtf8Ints(D, len); for (int i = 0; i < len; i++) { M2[i] = mod(C[i], d, n); } char* str = utf8IntsToString(M2, len); cout << "解密结果:" << str << endl; delete[] M; delete[] C; delete[] D; delete[] M2; delete[] str; return 0; }