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

7

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

#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
1个回答

11
unsigned char *p_str = "82019154470699086128524248488673846867876336512717";

BIGNUM *p = BN_bin2bn(p_str, sizeof(p_str), NULL);
请使用int BN_dec2bn(BIGNUM **a,const char *str)代替。
当您有一个byte数组(而不是以空字符结尾的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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接