vs2010使用C语言和openssl编写RSA加解密
时间: 2023-07-11 16:35:46 浏览: 60
以下是一个简单的示例程序,使用 OpenSSL 库进行 RSA 加解密,可以在 VS2010 中使用 C 语言编写。
```c
#include <stdio.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#define KEY_LENGTH 2048
#define PUB_EXP 3
#define PRIV_EXP "mykey.pem"
int main()
{
RSA *keypair = RSA_generate_key(KEY_LENGTH, PUB_EXP, NULL, NULL);
if (!keypair)
{
printf("Error generating RSA key!\n");
return -1;
}
// 保存私钥
FILE *priv_file = fopen(PRIV_EXP, "wb");
if (priv_file)
{
PEM_write_RSAPrivateKey(priv_file, keypair, NULL, NULL, 0, NULL, NULL);
fclose(priv_file);
printf("Private key saved to %s.\n", PRIV_EXP);
}
else
{
printf("Error saving private key!\n");
RSA_free(keypair);
return -1;
}
// 加密
const char *msg = "Hello, world!";
size_t msg_len = strlen(msg) + 1;
unsigned char enc_msg[KEY_LENGTH / 8];
int enc_msg_len = RSA_public_encrypt(msg_len, (unsigned char*)msg, enc_msg, keypair, RSA_PKCS1_PADDING);
if (enc_msg_len == -1)
{
printf("Error encrypting message!\n");
RSA_free(keypair);
return -1;
}
printf("Encrypted message: ");
for (int i = 0; i < enc_msg_len; i++)
{
printf("%02x", enc_msg[i]);
}
printf("\n");
// 解密
unsigned char dec_msg[KEY_LENGTH / 8];
int dec_msg_len = RSA_private_decrypt(enc_msg_len, enc_msg, dec_msg, keypair, RSA_PKCS1_PADDING);
if (dec_msg_len == -1)
{
printf("Error decrypting message!\n");
RSA_free(keypair);
return -1;
}
printf("Decrypted message: %s\n", dec_msg);
RSA_free(keypair);
return 0;
}
```
此示例程序生成一个 2048 位的 RSA 密钥对,并将私钥保存到 "mykey.pem" 文件中。然后,将一个字符串 "Hello, world!" 加密,并将加密后的消息打印出来。接着,解密加密后的消息,并将原始消息打印出来。