如何将 int 数组转换为 OpenSSL BIGNUM?

How to convert an array of int to an OpenSSL BIGNUM?

在 C++ 中,我尝试使用 OpenSSL 库将表示大整数的 int 数组转换为 BIGNUM。

包含大数的十六进制编码的字符串没问题,但我找不到如何用数组来实现。

#include <openssl/bn.h>

int main()
{
    uint32_t hash[4] = { 0x3506fa7d, 0x6bb2dbe9, 0x9041d8e5, 0x6ea31f6b };
    const char p_hash[] = "3506fa7d6bb2dbe99041d8e56ea31f6b";

    BIGNUM *bn_result1 = BN_new();
    BN_hex2bn(&bn_result1, p_hash);

    std::cout << "Big number as Dec: " << BN_bn2dec(bn_result1) << std::endl;
    std::cout << "Big number as Hex: " << BN_bn2hex(bn_result1) << std::endl;

    // How to convert hash[4] to BIGNUM bn_result2?
}

htobe32BN_bin2bn 的可能解决方案:

for(i=0; i<4; i++) {
    hash[i] = htobe32(hash[i]); /* BN_bin2bn needs big endian data */
}

BN_bin2bn((const unsigned char *)hash, (4*4), &bn_result2);

如果您确定主机字节顺序是大端字节序,则可以省略转换,但这样做会失去可移植性。

编辑:

这同样适用于小端版本 BN_lebin2bn 如果您的主机字节顺序是小端。