以下代码可以成功加密和解密我的数据。
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");
}