编写一段RSA算法生成五位数的公钥私钥的c语言代码,并测试生成的公钥私钥的正确性
时间: 2024-02-20 21:56:33 浏览: 73
rsa.rar_rsa_rsa加密 C语言_site:www.pudn.com
5星 · 资源好评率100%
以下是生成RSA算法五位数公钥私钥的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define MAX 1000000
int gcd(int a, int b) {
int tmp;
while (a % b != 0) {
tmp = b;
b = a % b;
a = tmp;
}
return b;
}
int is_prime(int n) {
if (n <= 1) {
return 0;
}
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int get_prime() {
int p;
do {
p = rand() % MAX + 1;
} while (!is_prime(p));
return p;
}
int mod_inverse(int a, int b) {
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) {
return 1;
}
while (a > 1) {
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0) {
x1 += b0;
}
return x1;
}
int main() {
srand(time(0));
int p = get_prime();
int q = get_prime();
int n = p * q;
int phi = (p - 1) * (q - 1);
int e = 2;
while (gcd(e, phi) != 1) {
e++;
}
int d = mod_inverse(e, phi);
printf("公钥: (%d, %d)\n", e, n);
printf("私钥: (%d, %d)\n", d, n);
return 0;
}
```
此代码会生成一个五位数的RSA算法公钥私钥,并输出到屏幕上。
为测试生成的公钥私钥的正确性,我们可以编写以下代码:
```c
#include <stdio.h>
#define MAX 1000000
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 p = 283;
int q = 467;
int n = p * q;
int phi = (p - 1) * (q - 1);
int e = 23;
int d = 4095;
int m = 12345;
int c = encrypt(m, e, n);
int m2 = decrypt(c, d, n);
printf("原文: %d\n", m);
printf("加密: %d\n", c);
printf("解密: %d\n", m2);
return 0;
}
```
此代码使用了公钥(e, n)对12345进行加密,并使用私钥(d, n)对密文进行解密,最后输出原文和解密后的明文。如果输出的解密后的明文与原文相同,则说明生成的公钥私钥是正确的。
阅读全文