rsa加密解密C语言代码
时间: 2023-12-02 14:40:11 浏览: 155
以下是一个简单的C语言实现RSA加密解密的代码,其中包括生成密钥、加密和解密三个部分:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#define MAX 1000
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int extend(int a, int b) {
int x1 = 1, y1 = 0, x2 = 0, y2 = 1, x, y, r, q;
while (b > 0) {
q = a / b;
r = a - q * b;
x = x1 - q * x2;
y = y1 - q * y2;
a = b;
b = r;
x1 = x2;
y1 = y2;
x2 = x;
y2 = y;
}
return x1;
}
int is_prime(int n) {
int i;
if (n <= 1) {
return 0;
}
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int generate_prime() {
int p;
do {
p = rand() % MAX;
} while (!is_prime(p));
return p;
}
void generate_key(int *p, int *q, int *n, int *t, int *e, int *d) {
srand(time(NULL));
*p = generate_prime();
*q = generate_prime();
*n = (*p) * (*q);
*t = ((*p) - 1) * ((*q) - 1);
do {
*e = rand() % (*t - 2) + 2;
} while (gcd(*e, *t) != 1);
*d = extend(*e, *t);
}
int fast_pow(int a, int b, int n) {
int ans = 1;
while (b > 0) {
if (b & 1) {
ans = (ans * a) % n;
}
a = (a * a) % n;
b >>= 1;
}
return ans;
}
void encrypt(int e, int n, char *plaintext, int *ciphertext) {
int i;
for (i = 0; i < strlen(plaintext); i++) {
ciphertext[i] = fast_pow(plaintext[i], e, n);
}
}
void decrypt(int d, int n, int *ciphertext, char *plaintext) {
int i;
for (i = 0; i < strlen(plaintext); i++) {
plaintext[i] = fast_pow(ciphertext[i], d, n);
}
}
int main() {
int p, q, n, t, e, d, i;
char plaintext[MAX];
int ciphertext[MAX];
generate_key(&p, &q, &n, &t, &e, &d);
printf("公钥为:(%d, %d)\n", e, n);
printf("私钥为:%d\n", d);
printf("请输入要加密的明文:");
scanf("%s", plaintext);
encrypt(e, n, plaintext, ciphertext);
printf("密文为:");
for (i = 0; i < strlen(plaintext); i++) {
printf("%d ", ciphertext[i]);
}
printf("\n请输入正确的密钥,密钥正确将解密上面的密文:");
scanf("%d", &d);
if (d == e) {
decrypt(d, n, ciphertext, plaintext);
printf("明文为:%s\n", plaintext);
} else {
printf("密钥错误,无法解密!\n");
}
return 0;
}
```
该代码实现了RSA加密解密的基本功能,包括生成密钥、加密和解密。用户可以输入要加密的明文,程序将输出密文,并要求用户输入正确的密钥进行解密。如果密钥正确,程序将输出解密后的明文,否则将输出密钥错误的提示信息。
阅读全文