用C语言实现RSA加解密算法
时间: 2023-08-08 19:13:32 浏览: 192
RSA加解密算法 C语言实现
好的,以下是用C语言实现RSA加解密算法的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <stdint.h>
// 定义大质数素数数组,数组长度为100
uint32_t PrimeList[100] = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541
};
// 定义欧拉函数,参数为两个质数
uint32_t Euler(uint32_t p, uint32_t q) {
return (p - 1) * (q - 1);
}
// 定义取模反元素函数
uint32_t ModInverse(uint32_t a, uint32_t b) {
uint32_t r, r1 = a, r2 = b;
uint32_t t, t1 = 0, t2 = 1;
while (r2 > 0) {
t = r1 / r2;
r = r1 - t * r2;
r1 = r2;
r2 = r;
t = t1 - t * t2;
t1 = t2;
t2 = t;
}
if (r1 == 1) {
if (t1 < 0) {
t1 += a;
}
return t1;
} else {
return 0;
}
}
// 定义素数判断函数
int IsPrime(uint32_t n) {
int i;
if (n < 2) {
return 0;
}
for (i = 0; i < 100; i++) {
if (n == PrimeList[i]) {
return 1;
}
if (n % PrimeList[i] == 0) {
return 0;
}
}
for (i = 251; i <= sqrt(n); i += 2) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
// 定义随机生成素数函数
uint32_t RandomPrime() {
uint32_t p;
do {
p = rand() % 65536 + 32768;
} while (!IsPrime(p));
return p;
}
// 定义生成RSA密钥对函数
void RSAKeyGen(uint32_t *p, uint32_t *q, uint32_t *n, uint32_t *e, uint32_t *d) {
srand((unsigned)time(NULL));
*p = RandomPrime();
*q = RandomPrime();
*n = *p * *q;
uint32_t phi = Euler(*p, *q);
do {
*e = rand() % phi;
} while (*e < 2 || *e >= phi || phi % *e == 0);
*d = ModInverse(phi, *e);
}
// 定义RSA加密函数
uint32_t RSAEncrypt(uint32_t m, uint32_t e, uint32_t n) {
uint32_t c = 1;
for (int i = 0; i < e; i++) {
c = (c * m) % n;
}
return c;
}
// 定义RSA解密函数
uint32_t RSADecrypt(uint32_t c, uint32_t d, uint32_t n) {
uint32_t m = 1;
for (int i = 0; i < d; i++) {
m = (m * c) % n;
}
return m;
}
int main() {
uint32_t p, q, n, e, d;
RSAKeyGen(&p, &q, &n, &e, &d);
printf("p = %u, q = %u, n = %u, e = %u, d = %u\n", p, q, n, e, d);
uint32_t m = 12345;
printf("m = %u\n", m);
uint32_t c = RSAEncrypt(m, e, n);
printf("c = %u\n", c);
uint32_t m2 = RSADecrypt(c, d, n);
printf("m2 = %u\n", m2);
return 0;
}
```
这段代码包括随机生成素数、生成RSA密钥对、RSA加密、RSA解密等多个函数。通过调用这些函数,可以实现RSA加解密算法。
阅读全文