用C语言写一段RSA加密算法
时间: 2023-12-29 19:53:19 浏览: 145
好的,请稍等一会,我会为您生成RSA加密算法的C语言代码。
以下为生成的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#define MAX_DIGIT 1000
#define MAX_PRIME 100
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 gcd(int a, int b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
int is_prime(int n) {
if (n <= 1) {
return 0;
}
if (n == 2 || n == 3) {
return 1;
}
if (n % 2 == 0 || n % 3 == 0) {
return 0;
}
int i = 5;
int w = 2;
while (i * i <= n) {
if (n % i == 0) {
return 0;
}
i += w;
w = 6 - w;
}
return 1;
}
int generate_prime(int *primes, int count) {
srand(time(NULL));
int index = 0;
while (index < count) {
int n = rand() % MAX_PRIME + 1;
if (is_prime(n)) {
primes[index] = n;
index++;
}
}
return primes[count - 1];
}
int main() {
int primes[2] = {0};
generate_prime(primes, 2);
int p = primes[0];
int q = primes[1];
int n = p * q;
int phi_n = (p - 1) * (q - 1);
int e = 65537;
while (gcd(e, phi_n) != 1) {
e++;
}
int d = 0;
int k = 1;
while (1) {
d = (phi_n * k + 1) / e;
if (e * d == phi_n * k + 1) {
break;
}
k++;
}
printf("p = %d\n", p);
printf("q = %d\n", q);
printf("n = %d\n", n);
printf("phi_n = %d\n", phi_n);
printf("e = %d\n", e);
printf("d = %d\n", d);
int m = 1234;
printf("m = %d\n", m);
int c = encrypt(m, e, n);
printf("c = %d\n", c);
int m2 = decrypt(c, d, n);
printf("m2 = %d\n", m2);
return 0;
}
```
该程序实现了RSA算法的加密和解密过程。其中,generate_prime()函数用于生成指定个数的素数,gcd()函数用于计算两个数的最大公约数,is_prime()函数用于判断一个数是否为素数,encrypt()函数用于加密明文,decrypt()函数用于解密密文。程序首先生成两个随机素数p和q,然后计算n=p*q和phi_n=(p-1)*(q-1),接着选择e=65537作为加密公钥,计算d作为解密私钥。最后,程序展示了一个简单的加密和解密示例。
阅读全文