RSA加密解密算法C语言
时间: 2023-11-23 20:54:51 浏览: 135
RSA加密解密算法是一种非对称加密算法,它是由Ron Rivest、Adi Shamir和Leonard Adleman在1977年提出的。RSA算法的安全性基于大数分解的困难性,即将一个大数分解成两个质数的乘积。RSA算法的加密过程是将明文先转换成数字,然后使用公钥进行加密,得到密文;解密过程是使用私钥对密文进行解密,得到明文。RSA算法在数字签名、密钥协商等领域有着广泛的应用。
以下是一个简单的C语言实现RSA加密解密算法的范例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#define PUBLIC_KEY_FILE "public_key.pem"
#define PRIVATE_KEY_FILE "private_key.pem"
int main()
{
RSA *rsa = NULL;
FILE *fp = NULL;
char *plain_text = "Hello, RSA!";
char *cipher_text = NULL;
char *decrypted_text = NULL;
int plain_text_len = strlen(plain_text);
int cipher_text_len = 0;
int decrypted_text_len = 0;
// 生成RSA密钥对
rsa = RSA_generate_key(1024, RSA_F4, NULL, NULL);
if (rsa == NULL) {
printf("Failed to generate RSA key pair!\n");
return -1;
}
// 将公钥写入文件
fp = fopen(PUBLIC_KEY_FILE, "w");
if (fp == NULL) {
printf("Failed to open public key file!\n");
return -1;
}
PEM_write_RSAPublicKey(fp, rsa);
fclose(fp);
// 将私钥写入文件
fp = fopen(PRIVATE_KEY_FILE, "w");
if (fp == NULL) {
printf("Failed to open private key file!\n");
return -1;
}
PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL);
fclose(fp);
// 加密明文
cipher_text_len = RSA_size(rsa);
cipher_text = (char *)malloc(cipher_text_len);
memset(cipher_text, 0, cipher_text_len);
RSA_public_encrypt(plain_text_len, (unsigned char *)plain_text, (unsigned char *)cipher_text, rsa, RSA_PKCS1_PADDING);
// 解密密文
decrypted_text_len = RSA_size(rsa);
decrypted_text = (char *)malloc(decrypted_text_len);
memset(decrypted_text, 0, decrypted_text_len); RSA_private_decrypt(cipher_text_len, (unsigned char *)cipher_text, (unsigned char *)decrypted_text, rsa, RSA_PKCS1_PADDING);
// 输出结果
printf("Plain text: %s\n", plain_text);
printf("Cipher text: ");
for (int i = 0; i < cipher_text_len; i++) {
printf("%02x", (unsigned char)cipher_text[i]);
}
printf("\n");
printf("Decrypted text: %s\n", decrypted_text);
// 释放资源
RSA_free(rsa);
free(cipher_text);
free(decrypted_text);
return 0;
}
```
阅读全文