用C++写一段RSA加密算法
时间: 2023-11-10 15:00:24 浏览: 75
基于C++的RSA加密算法
3星 · 编辑精心推荐
以下是C语言实现RSA加密算法的代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAX 1000
int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
int isprime(int n)
{
int i;
for (i = 2; i <= sqrt(n); i++)
{
if (n % i == 0)
return 0;
}
return 1;
}
int generate_prime(int n)
{
int i, p;
do
{
p = rand() % n;
} while (!isprime(p));
return p;
}
int main()
{
int p, q, e, d, n, phi_n, i, j, len;
char message[MAX], cipher[MAX], decrypted[MAX];
printf("Enter the message: ");
fgets(message, MAX, stdin);
len = strlen(message);
message[len - 1] = '\0';
p = generate_prime(100);
q = generate_prime(100);
n = p * q;
phi_n = (p - 1) * (q - 1);
do
{
e = rand() % phi_n;
} while (gcd(e, phi_n) != 1);
for (d = 1; d <= phi_n; d++)
{
if ((d * e) % phi_n == 1)
break;
}
printf("Public key: {%d, %d}\n", e, n);
printf("Private key: {%d, %d}\n", d, n);
for (i = 0; i < len; i++)
{
cipher[i] = pow(message[i], e) % n;
}
printf("Encrypted message: ");
for (i = 0; i < len; i++)
{
printf("%d ", cipher[i]);
}
printf("\n");
for (i = 0; i < len; i++)
{
decrypted[i] = pow(cipher[i], d) % n;
}
printf("Decrypted message: %s\n", decrypted);
return 0;
}
```
在这个实现中,首先输入待加密的明文,然后随机生成两个素数p和q,计算出n和phi_n。接着生成一个与phi_n互质的数e,使用扩展欧几里得算法计算出d。然后对明文中的每个字符进行加密,最后将加密后的密文解密并输出。
阅读全文