将作为字符串给出的大数字转换为 OpenSSL BIGNUM

Convert a big number given as a string to an OpenSSL BIGNUM

我正在尝试使用 OpenSSL 库将表示大整数的字符串 p_str 转换为 BIGNUM p

#include <stdio.h>
#include <openssl/bn.h>

int main ()
{
  /* I shortened the integer */
  unsigned char *p_str = "82019154470699086128524248488673846867876336512717";

  BIGNUM *p = BN_bin2bn(p_str, sizeof(p_str), NULL);

  BN_print_fp(stdout, p);
  puts("");

  BN_free(p);
  return 0;
}

编译它:

gcc -Wall -Wextra -g -o convert convert.c -lcrypto

但是,当我执行它时,我得到以下结果:

3832303139313534
unsigned char *p_str = "82019154470699086128524248488673846867876336512717";

BIGNUM *p = BN_bin2bn(p_str, sizeof(p_str), NULL);

改用int BN_dec2bn(BIGNUM **a, const char *str)

当你有一个 bytes 的数组(而不是 NULL 终止的 ASCII 字符串)时,你会使用 BN_bin2bn

手册页位于 BN_bin2bn(3)

正确的代码如下所示:

#include <stdio.h>
#include <openssl/bn.h>

int main ()
{
  static const
  char p_str[] = "82019154470699086128524248488673846867876336512717";

  BIGNUM *p = BN_new();
  BN_dec2bn(&p, p_str);

  char * number_str = BN_bn2hex(p);
  printf("%s\n", number_str);

  OPENSSL_free(number_str);
  BN_free(p);

  return 0;
}