【问题标题】:OpenSSL: BIGNUM's bin2bn doesn't allocate a new BIGNUM when output ptr is nullOpenSSL:当输出 ptr 为空时,BIGNUM 的 bin2bn 不会分配新的 BIGNUM
【发布时间】:2018-09-17 10:19:39
【问题描述】:

根据OpenSSL 1.1.0's manual,它说:

BN_bin2bn() 将 s 处长度为 len 的 big-endian 形式的正整数转换为 BIGNUM 并将其放在 ret 中。如果 ret 为 NULL,则创建一个新的 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
    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 签名。我不相信这对此有任何影响。如果我错了,请纠正我。

【问题讨论】:

  • 当这显然不是 C 代码时,你为什么要替换 C 标签?
  • @WeatherVane 因为这个问题不是 C++ 独有的。 OpenSSL 是纯 C 语言,使用 C 语言编码的人可能仍然需要回答同样的问题。

标签: c++ c openssl cryptography bignum


【解决方案1】:

好的。我想我想通了。如果retnullptr,那么返回值 将在bin2bn() 的返回中创建一个新的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;
}

如果我错了,请纠正我。

【讨论】:

  • 这个想法是函数返回值,因此您可以直接使用它(例如用于方法链接或表达式中)。争论只是为了节省空间;您可以重用缓冲区。希望这对你有意义:)
  • @MaartenBodewes 感谢您的解释。我可以想象它在某些情况下很有用,但仍然感觉多余。感谢您确认我做对了。干杯!
  • 不客气。与面向对象的语言相比,C 结构可能不太有用。除了分配它之外,您不能对引用做太多事情,但您至少可以在一行中执行eccsig_r 的声明和分配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多