Convert a large number as a string to OpenSSL BIGNUM

I am trying to convert a string p_str representing a large integer to BIGNUM p using the OpenSSL library.

 #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; } 

Compiled with:

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

But when I execute it, I get the following result:

 3832303139313534 
+5
source share
1 answer
 unsigned char *p_str = "82019154470699086128524248488673846867876336512717"; BIGNUM *p = BN_bin2bn(p_str, sizeof(p_str), NULL); 

Use int BN_dec2bn(BIGNUM **a, const char *str) instead.

You would use BN_bin2bn when you have a bytes array (and not an AULL string with a terminating NULL character).

The manual pages are located in BN_bin2bn(3) .

The correct code would look like this:

 #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; } 
+8
source

All Articles