c++实现RSA,参数p、q选取3位的十进制数;
时间: 2024-03-27 07:37:47 浏览: 64
RSA的实现(C++)
5星 · 资源好评率100%
以下是C++实现RSA加密和解密的代码,其中p和q分别选取了3位的十进制数:
```c++
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int modPow(int a, int b, int n) {
int res = 1;
while (b > 0) {
if (b & 1) res = (res * a) % n;
a = (a * a) % n;
b >>= 1;
}
return res;
}
bool isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
int generatePrime() {
int num = rand() % 900 + 100; // 生成3位随机数
while (!isPrime(num)) {
num = rand() % 900 + 100;
}
return num;
}
int generateE(int phi) {
int e = rand() % (phi - 2) + 2;
while (gcd(e, phi) != 1) {
e = rand() % (phi - 2) + 2;
}
return e;
}
int calculateD(int e, int phi) {
int d = 1;
while ((e * d) % phi != 1) {
d++;
}
return d;
}
int encrypt(int m, int e, int n) {
return modPow(m, e, n);
}
int decrypt(int c, int d, int n) {
return modPow(c, d, n);
}
int main() {
srand((unsigned)time(NULL)); // 初始化随机数种子
int p = generatePrime();
int q = generatePrime();
int n = p * q;
int phi = (p - 1) * (q - 1);
int e = generateE(phi);
int d = calculateD(e, phi);
cout << "p = " << p << endl;
cout << "q = " << q << endl;
cout << "n = " << n << endl;
cout << "phi = " << phi << endl;
cout << "e = " << e << endl;
cout << "d = " << d << endl;
int m, c;
cout << "Enter message to be encrypted: ";
cin >> m;
c = encrypt(m, e, n);
cout << "Encrypted message: " << c << endl;
m = decrypt(c, d, n);
cout << "Decrypted message: " << m << endl;
return 0;
}
```
在这个代码中,我们使用了随机数生成函数`rand()`,并用`srand((unsigned)time(NULL))`初始化了随机数种子,以确保每次运行程序时得到的随机数都是不同的。我们先生成两个3位的素数p和q,然后计算出它们的乘积n和欧拉函数phi。接着随机生成一个整数e,使得1 < e < phi且e与phi互质,然后计算出它的乘法逆元d。最后,我们输入要加密的明文m,计算出密文c,并输出加密和解密后的结果。
阅读全文