OpenSSL:当输出指针为空时,BIGNUM 的 bin2bn 不会分配新的 BIGNUM

OpenSSL: BIGNUM's bin2bn doesn't allocate a new BIGNUM when output ptr is null

根据OpenSSL 1.1.0's manual,它说:

BN_bin2bn() converts the positive integer in big-endian form of length len at s into a BIGNUM and places it in ret. If ret is NULL, a new BIGNUM is created.

但是在下面的最小示例中:

#include <iostream>
#include <boost/algorithm/hex.hpp>
#include <openssl/bn.h>
#include <vector>

int main()
{
    std::string in = "200ec31326d7a933222e3b43a7d6c920a1d2e8a74d1e6f4980ca78b2d9c1aaba6c2ad71f0f1d0cbb40695f27be048982589bccf30066a8735db4a6b0928925077e";
    std::vector<unsigned char> out;
    // convert hex to binary bytes
    boost::algorithm::unhex(in.begin(), in.end(), std::back_inserter(out));
    BIGNUM *eccsig_r = nullptr;
    // convert bytes to a BIGNUM object
    BN_bin2bn(&out[1],  32, eccsig_r);
    std::cout<<eccsig_r<<std::endl; // prints 0!
    return 0;
}

eccsig_r的指针地址保持0(或nullptr)。如果我理解手册上说的,应该是 eccsig_r 在调用 bin2bn() 之后再也不会 nullptr

为什么eccsig_r还是nullptr?我不明白这个。请指教。我在 Debian 9.

PS:为了全面披露,您在上面看到的十六进制是我序列化的简单 ECC 签名。我不认为这对此有任何影响。如有不妥请指正

好的。我想我明白了。如果 retnullptr,那么 return 值 将在 bin2bn() 的 return 中创建一个新的 BIGNUM。在我看来,这是一种奇怪的做事方式。我不明白其用途,但这有效:

#include <iostream>
#include <boost/algorithm/hex.hpp>
#include <openssl/bn.h>
#include <vector>

int main()
{
    std::string in = "200ec31326d7a933222e3b43a7d6c920a1d2e8a74d1e6f4980ca78b2d9c1aaba6c2ad71f0f1d0cbb40695f27be048982589bccf30066a8735db4a6b0928925077e";
    std::vector<unsigned char> out;
    // convert hex to binary bytes
    boost::algorithm::unhex(in.begin(), in.end(), std::back_inserter(out));
    BIGNUM *eccsig_r = nullptr;
    // convert bytes to a BIGNUM object
    eccsig_r = BN_bin2bn(&out[1],  32, nullptr);
    std::cout<<eccsig_r<<std::endl; // doesn't print zero anymore!
    return 0;
}

如有错误请指正