用c++语言写rsa加密,输入数字加密
时间: 2024-03-16 18:46:31 浏览: 25
以下是使用C++语言实现RSA加密算法,输入数字加密的示例代码:
```c++
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
// 求最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// 判断是否为质数
bool isPrime(int num) {
if (num < 2) {
return false;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
// 生成RSA密钥
void generateRSAKey(int p, int q, int &n, int &e, int &d) {
n = p * q; // 计算n
int phi = (p - 1) * (q - 1); // 计算欧拉函数phi(n)
do {
e = rand() % (phi - 2) + 2; // 随机生成一个整数e,2 <= e <= phi(n) - 1
} while (gcd(e, phi) != 1); // e和phi(n)要互质
int k = 1;
while ((k * phi + 1) % e != 0) { // 计算d,使得 (k * phi + 1) % e = 0
k++;
}
d = (k * phi + 1) / e; // 计算d
}
// RSA加密
string rsaEncrypt(int plainText, int n, int e) {
int c = (int)pow(plainText, e) % n; // 计算密文
return to_string(c);
}
// RSA解密
int rsaDecrypt(string cipherText, int n, int d) {
int c = stoi(cipherText); // 将字符串转换为整数
int m = (int)pow(c, d) % n; // 计算明文
return m;
}
int main() {
int p = 61; // 选取两个质数p和q
int q = 53;
int n, e, d;
generateRSAKey(p, q, n, e, d); // 生成RSA密钥
int plainText;
cout << "请输入要加密的数字:";
cin >> plainText;
string cipherText = rsaEncrypt(plainText, n, e); // RSA加密
cout << "加密后的结果:" << cipherText << endl;
int decryptedText = rsaDecrypt(cipherText, n, d); // RSA解密
cout << "解密后的结果:" << decryptedText << endl;
return 0;
}
```
这段代码实现了RSA加密和解密功能,输入数字进行加密。输入要加密的数字后,程序会输出加密后的结果和解密后的结果。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)