rsa加解密算法c语言
时间: 2023-11-18 11:56:48 浏览: 111
RSA加解密算法 C语言实现
RSA加解密算法是一种非对称加密算法,它的安全性基于大数分解的困难性。RSA算法的加密和解密过程都需要使用到公钥和私钥,其中公钥用于加密,私钥用于解密。下面是RSA加解密算法的C语言实现:
1. 生成公钥和私钥
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#define MAX_PRIME 1000000
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 gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
srand(time(NULL));
int p, q, n, phi, e, d;
do {
p = rand() % MAX_PRIME + 1;
} while (!is_prime(p));
do {
q = rand() % MAX_PRIME + 1;
} while (!is_prime(q) || p == q);
n = p * q;
phi = (p - 1) * (q - 1);
do {
e = rand() % phi + 1;
} while (gcd(e, phi) != 1);
for (int i = 1; i < phi; i++) {
if ((i * e) % phi == 1) {
d = i;
break;
}
}
printf("Public key: (%d, %d)\n", e, n);
printf("Private key: (%d, %d)\n", d, n);
return 0;
}
```
2. 加密和解密
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int mod_pow(int base, int exponent, int modulus) {
int result = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % modulus;
}
base = (base * base) % modulus;
exponent /= 2;
}
return result;
}
int main() {
int e, d, n, len;
char message[100];
printf("Enter public key (e, n): ");
scanf("%d %d", &e, &n);
printf("Enter private key (d, n): ");
scanf("%d %d", &d, &n);
printf("Enter message to encrypt: ");
scanf("%s", message);
len = strlen(message);
int encrypted[len], decrypted[len];
for (int i = 0; i < len; i++) {
encrypted[i] = mod_pow(message[i], e, n);
decrypted[i] = mod_pow(encrypted[i], d, n);
}
printf("Encrypted message: ");
for (int i = 0; i < len; i++) {
printf("%d ", encrypted[i]);
}
printf("\nDecrypted message: ");
for (int i = 0; i < len; i++) {
printf("%c", decrypted[i]);
}
printf("\n");
return 0;
}
```
阅读全文