views:

128

answers:

1

I'm trying to use the BN_* functions in OpenSSL. Specifically, I have the following code:

#import <openssl/bn.h>
BIGNUM * num = BN_new();
BN_set_word(num, 42);
char * buffer = malloc((BN_num_bytes(num)+1) * sizeof(char));
buffer[BN_num_bytes(num)] = '\0';
int len = BN_bn2bin(num, buffer);
printf("42 in binary is %s\n", buffer);

However, when I do this, I don't get a string of ones and zeros. Instead it prints "42 in binary is *". As far as I can tell, and from the very limited number of examples available on the web that I've compared this to, I've implemented this correctly.

Any ideas why it isn't working?

+3  A: 

BN_bn2bin doesn't create a printable string - instead, it creates a representation that is truly binary (i.e. a sequence of bits). More specifically, it createas a big-endian representation of the number. Since 42 fits into one byte, you get one byte 0x2a, which is "*" in ASCII.

If you want a 0/1 representation, you need to iterate over all bytes, and do the printing yourself (e.g. with shifting or a lookup table).

Martin v. Löwis
doh! I should've thought of looking at the ascii value! I was assuming that since it's listed in the docs next to bn2hex and bn2dec that it would work the same way. Bummer... Thanks for clarifying. =)
Dave DeLong