我如何加密&使用PEM解密数据 - OPENSSL,C,BIO

时间:2013-02-24 15:41:48

标签: c encryption openssl pem

以下代码可以成功加密和解密我的数据。

size_t pri_len;
size_t pub_len;
char *pri_key;
char *pub_key;
char message[AES_KEY_SIZE];
char *encrypted = NULL;
char *decrypted = NULL;

int pub_exp = 37;

RSA *keyPair = RSA_generate_key(2048,pub_exp,NULL,NULL);
BIO *pri = BIO_new(BIO_s_mem());
BIO *pub = BIO_new(BIO_s_mem());
//char passwordTemp[16] = "helloworld";
//pem_password_cb();

PEM_write_bio_RSAPrivateKey(pri,keyPair,NULL,NULL,0,NULL,NULL);
PEM_write_bio_RSAPublicKey(pub,keyPair);

pri_len = BIO_pending(pri);
pub_len = BIO_pending(pub);

pri_key = (char*)malloc(pri_len + 1);
pub_key = (char*)malloc(pub_len + 1);

BIO_read(pri,pri_key,pri_len);
BIO_read(pub,pub_key,pub_len);

pri_key[pri_len] = '\0';
pub_key[pub_len] = '\0';

//generate random number to encrypt
unsigned char randNum[AES_KEY_SIZE];
this->generateRandomNum(randNum,AES_KEY_SIZE);

char *encrypt2 =(char*) malloc(RSA_size(keyPair));
int encrypt_len2;
if((encrypt_len2 = RSA_public_encrypt(AES_KEY_SIZE,randNum,(unsigned char*)encrypt2,keyPair, RSA_PKCS1_OAEP_PADDING))==-1)
{
    printf("error");
}
else
{
    printf("encrypt success");
}

char *decrypt2 = (char*) malloc(RSA_size(keyPair));
if(RSA_private_decrypt(encrypt_len2,(unsigned char*) encrypt2, (unsigned char*) decrypt2,keyPair,  RSA_PKCS1_OAEP_PADDING)==-1)
{
    printf("error");
}
else
{
    printf("decrypt success");
}

但是,如果我想存储我的PEM文件并在以后使用它,如何再次使用我的密钥来加密和解密数据?

我发现以下函数用于恢复我的RSA密钥,但是,如果我使用其中任何一个密钥来解密我的数据,则会发生错误...

:尝试读取或写入受保护的内存

RSA *keyPair2 = PEM_read_bio_RSAPrivateKey(pri,NULL,0,NULL);
RSA *keyPair3 = PEM_read_bio_RSAPublicKey(pub,NULL,0,NULL);

char *decrypt2 = (char*) malloc(RSA_size(keyPair2));
if(RSA_private_decrypt(encrypt_len2,(unsigned char*) encrypt2, (unsigned char*) decrypt2,keyPair2,  RSA_PKCS1_OAEP_PADDING)==-1)
{
    printf("error");
}
else
{
    printf("decrypt success");
}

1 个答案:

答案 0 :(得分:0)

您需要使用私钥加密密钥,然后将其保留在文件中。但是,私人的安全性很重要。您可以考虑PKCS#8安全地存储私钥。