为什么在我的代码中调用EVP_PKEY_assign_RSA()或EVP_PKEY_set1_RSA()之后,RSA_size()和EVP_PKEY_size()会崩溃?
openssl版本是1.10。
如果我没有调用EVP_PKEY_assign_RSA()或EVP_PKEY_set1_RSA(),程序将正确运行。
另外,我认为这两个函数都用于从EVP_PKEY设置RSA_st,我对这两个函数有误解吗?
void testfun(char **argc) {
OpenSSL_add_all_algorithms();
EVP_PKEY *prikey = nullptr, *pubkey = nullptr;
BIO *prifile = nullptr, *pubfile = nullptr;
RSA *pubrsa = nullptr, *prirsa = nullptr, *newra = nullptr;
prifile = BIO_new_file(argc[1], "r");
char passwd[] = "1111";
prikey = EVP_PKEY_new();
prikey = PEM_read_bio_PrivateKey(prifile, nullptr, 0, passwd);
prirsa = RSA_new();
/* all those code block combination will cause segmentation fault
* 1-3
* 1-4
* 2-3
* 2-4
* and output will be correct if i only use code block 3
* */
//1
//cout << EVP_PKEY_assign_RSA(prikey, prirsa) << endl;
//2
//cout << EVP_PKEY_set1_RSA(prikey, prirsa) << endl;
//3
//cout << EVP_PKEY_size(prikey) << endl;
//4
//cout << RSA_size(prirsa) << endl;
}
RSA_size
崩溃
RSA_size
需要一个RSA指针和返回键的模大小-所提供的密钥必须被初始化,根据https://www.openssl.org/docs/man1.0.2/man3/RSA_size.html rsa->n
必须不为NULL。您RSA_new
不会创建密钥-它只会分配结构。因此,您不能调用从不存在的键中提取大小的函数。
EVP_PKEY_size
崩溃
EVP_PKEY_size
崩溃的原因基本相同-您将不正确的密钥分配给现有的正确密钥(假设您在中提供了正确的密钥)BIO_new_file
。
因此,您可能想要的代码是:
生成具有密码1111的RSA密钥,如下所示:
openssl genrsa -des3 -out private.pem 2048
使用以下代码运行该程序:
#include <iostream>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <cassert>
int main() {
OpenSSL_add_all_algorithms();
// UNUSED
// *pubkey = nullptr;
// *pubfile = nullptr;
// RSA *pubrsa = nullptr, *prirsa = nullptr, *newra = nullptr;
BIO * prifile = BIO_new_file("../private.pem", "r");
assert(prifile);
char passwd[] = "1111";
//prikey = EVP_PKEY_new(); // why allocate if you assign it somewhere else? memory leak!
EVP_PKEY * prikey = PEM_read_bio_PrivateKey(prifile, nullptr, 0, passwd);
assert(prikey);
//1
//std::cout << EVP_PKEY_assign_RSA(prikey, prirsa) << std::endl;
//2
//std::cout << EVP_PKEY_set1_RSA(prikey, prirsa) << std::endl;
//3 Should correctly output 256 (modulo size in bytes)
std::cout << EVP_PKEY_size(prikey) << std::endl;
//4
//std::cout << RSA_size(prirsa) << std::endl;
std::cout << "done\n";
return 0;
}
你并不需要EVP_PKEY_assign_RSA
,也不EVP_PKEY_set1_RSA
看你的关键。该功能PEM_read_bio_PrivateKey
为您完成所有这些工作!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句