rsa加密算法代码C语言
时间: 2023-10-11 08:08:05 浏览: 86
RSA加密算法,C语言实现
以下是一个简单的RSA加密算法C语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#define RSA_KEY_SIZE 2048
int main() {
// 生成RSA密钥对
RSA *rsa = RSA_generate_key(RSA_KEY_SIZE, RSA_F4, NULL, NULL);
if (!rsa) {
printf("failed to generate RSA key pair\n");
return -1;
}
// 将公钥和私钥分别保存到文件中
FILE *fp = fopen("public_key.pem", "w");
if (!fp) {
printf("failed to open file public_key.pem\n");
return -1;
}
PEM_write_RSAPublicKey(fp, rsa);
fclose(fp);
fp = fopen("private_key.pem", "w");
if (!fp) {
printf("failed to open file private_key.pem\n");
return -1;
}
PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, NULL, NULL);
fclose(fp);
// 加密和解密测试
const char *message = "Hello World!";
int message_len = strlen(message);
// 加密
int encrypted_size = RSA_size(rsa);
unsigned char *encrypted = malloc(encrypted_size);
int result = RSA_public_encrypt(message_len, (unsigned char *)message, encrypted, rsa, RSA_PKCS1_PADDING);
if (result == -1) {
printf("failed to encrypt message\n");
return -1;
}
// 解密
int decrypted_size = RSA_size(rsa);
unsigned char *decrypted = malloc(decrypted_size);
result = RSA_private_decrypt(result, encrypted, decrypted, rsa, RSA_PKCS1_PADDING);
if (result == -1) {
printf("failed to decrypt message\n");
return -1;
}
printf("Original message: %s\n", message);
printf("Decrypted message: %s\n", decrypted);
// 释放RSA密钥对和加解密缓冲区
RSA_free(rsa);
free(encrypted);
free(decrypted);
return 0;
}
```
该代码使用OpenSSL库,首先生成一个RSA密钥对,然后将公钥和私钥保存到文件中。接着,使用公钥对一条消息进行加密,再使用私钥对密文进行解密,并输出原始消息和解密后的消息。最后,释放RSA密钥对和加解密缓冲区。
阅读全文