使用EVP_PKEY_assign_RSA()或EVP_PKEY_set1_RSA()之后,RSA_size()和EVP_PKEY_size()出现段错误

siqian Wei

为什么在我的代码中调用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;
}
森林Rumcajs

RSA_size 崩溃

RSA_size需要一个RSA指针和返回键的模大小-所提供的密钥必须被初始化,根据https://www.openssl.org/docs/man1.0.2/man3/RSA_size.html rsa->n必须为NULLRSA_new不会创建密钥-它只会分配结构。因此,您不能调用从不存在的键中提取大小的函数。

EVP_PKEY_size 崩溃

EVP_PKEY_size崩溃的原因基本相同-您将不正确的密钥分配给现有的正确密钥(假设您在中提供了正确的密钥)BIO_new_file

因此,您可能想要的代码是:

  1. 生成具有密码1111的RSA密钥,如下所示:

    openssl genrsa -des3 -out private.pem 2048

  2. 使用以下代码运行该程序:

    #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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章