rsa加密算法C++
时间: 2023-07-11 08:05:46 浏览: 108
RSA加密算法是一种非对称加密算法,通过生成公钥和私钥,使用公钥加密信息,只有使用相应的私钥才能解密。下面是一个简单的RSA加密实现的C++代码示例:
```c++
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
bool is_prime(int num)
{
if (num < 2) {
return false;
}
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
int gcd(int a, int b)
{
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int generate_prime()
{
int num;
do {
num = rand() % 100 + 1;
} while (!is_prime(num));
return num;
}
int generate_coprime(int phi_n)
{
int e;
do {
e = rand() % (phi_n - 2) + 2;
} while (gcd(e, phi_n) != 1);
return e;
}
int extended_euclidean(int a, int b, int& x, int& y)
{
if (b == 0) {
x = 1;
y = 0;
return a;
}
int x1, y1;
int d = extended_euclidean(b, a % b, x1, y1);
x = y1;
y = x1 - (a / b) * y1;
return d;
}
int modular_inverse(int a, int m)
{
int x, y;
extended_euclidean(a, m, x, y);
return (x + m) % m;
}
int generate_keys(int& n, int& e, int& d)
{
srand(time(NULL));
int p = generate_prime();
int q = generate_prime();
n = p * q;
int phi_n = (p - 1) * (q - 1);
e = generate_coprime(phi_n);
d = modular_inverse(e, phi_n);
}
int encrypt(int m, int e, int n)
{
int c = 1;
for (int i = 0; i < e; i++) {
c = (c * m) % n;
}
return c;
}
int decrypt(int c, int d, int n)
{
int m = 1;
for (int i = 0; i < d; i++) {
m = (m * c) % n;
}
return m;
}
int main()
{
int n, e, d;
generate_keys(n, e, d);
cout << "Public key: (" << n << ", " << e << ")" << endl;
cout << "Private key: (" << n << ", " << d << ")" << endl;
int m;
cout << "Enter a message to encrypt: ";
cin >> m;
int c = encrypt(m, e, n);
cout << "Encrypted message: " << c << endl;
int decrypted_m = decrypt(c, d, n);
cout << "Decrypted message: " << decrypted_m << endl;
return 0;
}
```
这个实现采用了随机生成素数的方式生成公钥和私钥,然后使用公钥加密和私钥解密。注意,这个实现仅仅是一个简单的示例,实际应用中还需要考虑更多的安全性问题,比如选择更大的素数、采用更复杂的生成密钥方式等等。
阅读全文