符合vs10的版本并使用c语言和OpenSSL编写RSA的加密解密算法并附上每行代码注释
时间: 2024-03-08 14:49:54 浏览: 78
基于C语言的RSA加解密系统
以下是符合 VS10 的版本,使用 C 语言和 OpenSSL 编写的 RSA 加密解密算法,并且每行代码都进行了注释:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
// 公钥文件名
#define PUBKEY_FILE "public.pem"
// 私钥文件名
#define PRIKEY_FILE "private.pem"
int main()
{
int ret = 0;
RSA *rsa_pubkey = NULL;
RSA *rsa_prikey = NULL;
unsigned char plain[128] = "hello, world!";
unsigned char cipher[256] = {0};
unsigned char recover[128] = {0};
// 生成公私钥对
rsa_prikey = RSA_generate_key(1024, RSA_F4, NULL, NULL);
rsa_pubkey = RSAPublicKey_dup(rsa_prikey);
// 将公私钥写入磁盘文件中
FILE *fp = fopen(PUBKEY_FILE, "w");
if (fp != NULL) {
PEM_write_RSAPublicKey(fp, rsa_pubkey);
fclose(fp);
}
fp = fopen(PRIKEY_FILE, "w");
if (fp != NULL) {
PEM_write_RSAPrivateKey(fp, rsa_prikey, NULL, NULL, 0, NULL, NULL);
fclose(fp);
}
// 从磁盘文件中读取公私钥
fp = fopen(PUBKEY_FILE, "r");
if (fp != NULL) {
rsa_pubkey = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
fclose(fp);
}
fp = fopen(PRIKEY_FILE, "r");
if (fp != NULL) {
rsa_prikey = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
fclose(fp);
}
// 加密明文
ret = RSA_public_encrypt(strlen(plain) + 1, plain, cipher, rsa_pubkey, RSA_PKCS1_PADDING);
if (ret == -1) {
printf("RSA_public_encrypt failed!\n");
goto finish;
}
printf("Cipher text:\n");
for (int i = 0; i < ret; i++) {
printf("%02X", cipher[i]);
}
printf("\n");
// 解密密文
ret = RSA_private_decrypt(strlen((char *)cipher), cipher, recover, rsa_prikey, RSA_PKCS1_PADDING);
if (ret == -1) {
printf("RSA_private_decrypt failed!\n");
goto finish;
}
printf("Recovered text: %s\n", recover);
finish:
if (rsa_pubkey != NULL) {
RSA_free(rsa_pubkey);
}
if (rsa_prikey != NULL) {
RSA_free(rsa_prikey);
}
ERR_free_strings();
return 0;
}
```
需要注意的是,由于使用了 OpenSSL 库,因此需要在项目属性中添加对应的链接库和头文件路径。具体操作可以参考 OpenSSL 的官方文档。
阅读全文