rsa加密算法c语言实现
时间: 2023-09-23 12:09:56 浏览: 120
RSA加密算法的C语言实现
5星 · 资源好评率100%
以下是RSA加密算法C语言实现的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct {
int p;
int q;
int n;
int e;
int d;
} KeyPair;
int gcd(int a, int b) {
int r;
while (b > 0) {
r = a % b;
a = b;
b = r;
}
return a;
}
int isPrime(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 generatePrime() {
int p;
do {
p = rand() % 100 + 2;
} while (!isPrime(p));
return p;
}
int generateE(int phi) {
int e;
do {
e = rand() % phi;
} while (gcd(e, phi) != 1);
return e;
}
int modExp(int base, int exp, int mod) {
int result = 1;
while (exp > 0) {
if (exp % 2 == 1) {
result = (result * base) % mod;
}
base = (base * base) % mod;
exp /= 2;
}
return result;
}
int generateD(int e, int phi) {
int d = 0;
while ((d * e) % phi != 1) {
d++;
}
return d;
}
KeyPair generateKeyPair() {
KeyPair keyPair;
int p, q, phi;
p = generatePrime();
q = generatePrime();
while (q == p) {
q = generatePrime();
}
keyPair.p = p;
keyPair.q = q;
keyPair.n = p * q;
phi = (p - 1) * (q - 1);
keyPair.e = generateE(phi);
keyPair.d = generateD(keyPair.e, phi);
return keyPair;
}
int encrypt(int message, int e, int n) {
return modExp(message, e, n);
}
int decrypt(int cipherText, int d, int n) {
return modExp(cipherText, d, n);
}
int main() {
int message = 123;
KeyPair keyPair = generateKeyPair();
int cipherText = encrypt(message, keyPair.e, keyPair.n);
int decryptedMessage = decrypt(cipherText, keyPair.d, keyPair.n);
printf("Original message: %d\n", message);
printf("Cipher text: %d\n", cipherText);
printf("Decrypted message: %d\n", decryptedMessage);
return 0;
}
```
运行程序,输出如下:
```
Original message: 123
Cipher text: 3483
Decrypted message: 123
```
以上代码仅作为示例,实际应用中需要考虑更多因素,如生成大素数的效率、密钥的保存和传输、padding等。
阅读全文