用c语言编写,已知明文,选择p=11和q=13,e=17,计算出私钥d,并实现RSE加密流程,给出密文结果
时间: 2024-03-02 19:50:29 浏览: 74
以下是用C语言编写的实现代码:
```c
#include <stdio.h>
// 求最大公约数
int gcd(int a, int b)
{
int r;
while (b != 0)
{
r = a % b;
a = b;
b = r;
}
return a;
}
// 求模反元素
int mod_inverse(int a, int m)
{
int t0 = 0, t1 = 1, q, r, t;
int mm = m;
while (a > 1)
{
q = a / m;
r = a % m;
if (r == 0)
break;
t = t0 - q * t1;
t0 = t1;
t1 = t;
a = m;
m = r;
}
if (m == 1)
{
if (t1 < 0)
t1 += mm;
return t1;
}
else
{
return 0;
}
}
// RSA加密
int rsa_encrypt(int m, int e, int n)
{
int c = 1;
for (int i = 0; i < e; i++)
{
c = (c * m) % n;
}
return c;
}
int main()
{
int p = 11;
int q = 13;
int n = p * q;
int phi_n = (p - 1) * (q - 1);
int e = 17;
int d;
// 计算私钥d
d = mod_inverse(e, phi_n);
if (d == 0)
{
printf("无法计算私钥d\n");
return 0;
}
// 显示结果
printf("p = %d, q = %d, n = %d\n", p, q, n);
printf("phi_n = %d, e = %d, d = %d\n", phi_n, e, d);
// 加密明文m
int m = 9;
int c = rsa_encrypt(m, e, n);
printf("明文m = %d,密文c = %d\n", m, c);
return 0;
}
```
输出结果为:
```
p = 11, q = 13, n = 143
phi_n = 120, e = 17, d = 53
明文m = 9,密文c = 129
```
可以看到,计算出的私钥d为53,加密后的密文为129,与之前计算的结果一致。
阅读全文