c++实现RSA算法
时间: 2023-11-25 09:50:17 浏览: 88
以下是使用C++实现RSA算法的代码示例:
```cpp
#include <iostream>
#include <cmath>
#include <cstring>
using namespace std;
// 判断一个数是否为质数
bool is_prime(int n) {
if (n < 2) return false;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) return false;
}
return true;
}
// 求最大公约数
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
// 扩展欧几里得算法
int exgcd(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
int d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
// 求逆元
int inv(int a, int p) {
int x, y;
exgcd(a, p, x, y);
return (x % p + p) % p;
}
// 加密
int encrypt(int m, int e, int n) {
return (int)pow(m, e) % n;
}
// 解密
int decrypt(int c, int d, int n) {
return (int)pow(c, d) % n;
}
// 生成公钥和私钥
void generate_key(int p, int q, int &n, int &e, int &d) {
n = p * q;
int phi = (p - 1) * (q - 1);
for (int i = 2; i < phi; i++) {
if (gcd(i, phi) == 1) {
e = i;
break;
}
}
d = inv(e, phi);
}
int main() {
int p, q, n, e, d;
cout << "请输入两个质数p和q:" << endl;
cin >> p >> q;
if (!is_prime(p) || !is_prime(q)) {
cout << "p和q必须为质数!" << endl;
return 0;
}
generate_key(p, q, n, e, d);
cout << "公钥为:" << "(" << e << ", " << n << ")" << endl;
cout << "私钥为:" << "(" << d << ", " << n << ")" << endl;
int m, c;
cout << "请输入要加密的明文m:" << endl;
cin >> m;
c = encrypt(m, e, n);
cout << "加密后的密文为:" << c << endl;
m = decrypt(c, d, n);
cout << "解密后的明文为:" << m << endl;
return 0;
}
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)