C语言源代码RSA使用中国剩余定理对输入的文本型消息进行加解密
时间: 2023-07-11 22:03:35 浏览: 109
以下是C语言源代码RSA使用中国剩余定理对输入的文本型消息进行加解密的示例:
```c
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
// 求模反元素
long long int modReverse(long long int a, long long int m) {
long long int m0 = m, t, q;
long long int x0 = 0, x1 = 1;
if (m == 1)
return 0;
while (a > 1) {
q = a / m;
t = m;
m = a % m, a = t;
t = x0;
x0 = x1 - q * x0;
x1 = t;
}
if (x1 < 0)
x1 += m0;
return x1;
}
// 中国剩余定理
long long int chineseRemainderTheorem(long long int *a, long long int *m, int n) {
long long int M = 1, result = 0;
int i;
for (i = 0; i < n; i++)
M *= m[i];
for (i = 0; i < n; i++) {
long long int Mi = M / m[i];
result += a[i] * modReverse(Mi, m[i]) * Mi;
}
return result % M;
}
// 计算幂余
long long int modularExponentiation(long long int base, long long int exponent, long long int modulus) {
long long int result = 1;
base = base % modulus;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % modulus;
}
exponent = exponent >> 1;
base = (base * base) % modulus;
}
return result;
}
// 判断素数
int isPrime(long long int number) {
int i;
if (number == 2 || number == 3) {
return 1;
}
if (number % 2 == 0 || number == 1) {
return 0;
}
for (i = 3; i <= sqrt(number); i += 2) {
if (number % i == 0) {
return 0;
}
}
return 1;
}
// 生成公钥和私钥
void generateKeys(long long int p, long long int q, long long int *n, long long int *e, long long int *d) {
long long int phi = (p - 1) * (q - 1);
*n = p * q;
*e = 2;
while (*e < phi) {
if (isPrime(*e) && phi % *e != 0) {
break;
}
*e = *e + 1;
}
*d = modReverse(*e, phi);
}
// 加密
void encrypt(char *message, long long int *encryptedMessage, long long int e, long long int n) {
int i;
for (i = 0; i < strlen(message); i++) {
encryptedMessage[i] = modularExponentiation(message[i], e, n);
}
}
// 解密
void decrypt(long long int *encryptedMessage, int length, long long int d, long long int n, char *decryptedMessage) {
int i;
for (i = 0; i < length; i++) {
decryptedMessage[i] = modularExponentiation(encryptedMessage[i], d, n);
}
}
int main() {
long long int p, q, n, e, d;
char message[100];
long long int encryptedMessage[100];
char decryptedMessage[100];
printf("Enter two prime numbers: ");
scanf("%lld %lld", &p, &q);
generateKeys(p, q, &n, &e, &d);
printf("Public key: (%lld,%lld)\nPrivate key: (%lld,%lld)\n", n, e, n, d);
printf("Enter a message to encrypt: ");
scanf("%s", message);
encrypt(message, encryptedMessage, e, n);
printf("Encrypted message: ");
int i;
for (i = 0; i < strlen(message); i++) {
printf("%lld ", encryptedMessage[i]);
}
decrypt(encryptedMessage, strlen(message), d, n, decryptedMessage);
printf("\nDecrypted message: %s\n", decryptedMessage);
return 0;
}
```
在此示例中,我们首先生成了公钥和私钥,然后对输入的消息进行加密,最后解密加密后的消息,以确保正确性。请注意,该示例仅适用于短消息,因为在对长消息进行加密时,加密后的消息长度可能会超过n,从而导致中国剩余定理无法正常工作。
阅读全文