C语言源代码RSA对分割后的字符串加解密
时间: 2023-08-23 07:03:39 浏览: 134
以下是一个使用C语言实现RSA加解密的示例代码,可以对分割后的字符串进行加解密:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#define MAXLEN 10000
#define BLOCKSIZE 3
/* 辗转相除法求最大公因数 */
int gcd(int a, int b) {
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}
/* 扩展欧几里得算法求乘法逆元 */
int exgcd(int a, int b, int *x, int *y) {
if (b == 0) {
*x = 1;
*y = 0;
return a;
}
else {
int r = exgcd(b, a % b, x, y);
int t = *x;
*x = *y;
*y = t - a / b * (*y);
return r;
}
}
/* 判断一个数是否为素数 */
int isprime(int n) {
int i;
if (n < 2) {
return 0;
}
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
/* 生成一个指定位数的素数 */
int generate_prime(int bits) {
int p;
do {
p = rand() % (int)pow(10, bits) + (int)pow(10, bits - 1);
} while (!isprime(p));
return p;
}
/* 生成RSA公私钥对 */
void generate_key(int bits, int *p, int *q, int *n, int *e, int *d) {
int phi, x, y;
do {
*p = generate_prime(bits / 2);
*q = generate_prime(bits / 2);
*n = *p * *q;
phi = (*p - 1) * (*q - 1);
*e = rand() % phi;
} while (gcd(phi, *e) != 1);
exgcd(*e, phi, &x, &y);
*d = (x % phi + phi) % phi;
}
/* 加密一个字符 */
int encrypt_char(int c, int e, int n) {
int i, r = 1;
for (i = 0; i < e; i++) {
r = (r * c) % n;
}
return r;
}
/* 解密一个字符 */
int decrypt_char(int c, int d, int n) {
int i, r = 1;
for (i = 0; i < d; i++) {
r = (r * c) % n;
}
return r;
}
/* 加密一个字符串 */
void encrypt(char *msg, int len, int e, int n, int *ciphertext, int *ciphertext_len) {
int i, j, c;
*ciphertext_len = 0;
for (i = 0; i < len; i += BLOCKSIZE) {
c = 0;
for (j = 0; j < BLOCKSIZE; j++) {
if (i + j < len) {
c = c * 256 + msg[i + j];
}
else {
c = c * 256;
}
}
ciphertext[(*ciphertext_len)++] = encrypt_char(c, e, n);
}
}
/* 解密一个字符串 */
void decrypt(int *ciphertext, int ciphertext_len, int d, int n, char *msg, int *msg_len) {
int i, j, c;
*msg_len = 0;
for (i = 0; i < ciphertext_len; i++) {
c = decrypt_char(ciphertext[i], d, n);
for (j = BLOCKSIZE - 1; j >= 0; j--) {
if (*msg_len < MAXLEN) {
msg[(*msg_len)++] = (c >> (8 * j)) & 0xFF;
}
}
}
}
int main() {
srand((unsigned)time(NULL));
int bits = 512;
int p, q, n, e, d;
generate_key(bits, &p, &q, &n, &e, &d);
printf("p = %d\nq = %d\nn = %d\ne = %d\nd = %d\n", p, q, n, e, d);
char msg[MAXLEN], msg2[MAXLEN];
int ciphertext[MAXLEN], ciphertext_len, msg_len;
printf("Enter message: ");
gets(msg);
int len = strlen(msg);
encrypt(msg, len, e, n, ciphertext, &ciphertext_len);
decrypt(ciphertext, ciphertext_len, d, n, msg2, &msg_len);
msg2[msg_len] = '\0';
printf("Ciphertext: ");
int i;
for (i = 0; i < ciphertext_len; i++) {
printf("%d ", ciphertext[i]);
}
printf("\n");
printf("Decrypted message: %s\n", msg2);
return 0;
}
```
该程序会首先生成一个512位的RSA公私钥对,然后等待用户输入要加密的字符串,将字符串分成若干个3个字符一组的块,对每个块进行加密,最终输出加密后的密文和解密后的明文。注意:这个程序只是演示了如何使用RSA加密和解密一个字符串,实际应用中需要考虑安全性等问题。
阅读全文