21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

*outsz = BN_num_bytes(b);<br />

if (BN_is_negative(b)) {<br />

(*outsz)++;<br />

if (!(ret = (unsigned char *)malloc(*outsz))) return 0;<br />

BN_bn2bin(b, ret + 1);<br />

ret[0] = 0x80;<br />

} else {<br />

if (!(ret = (unsigned char *)malloc(*outsz))) return 0;<br />

BN_bn2bin(b, ret);<br />

}<br />

return ret;<br />

}<br />

Remember that the binary format used by a BIGNUM object is bigendian,<br />

so if you wish to take the binary output and put it in an integer<br />

on a little-endian architecture (such as an Intel x86 machine), you<br />

must byte-swap each word.<br />

If you wish to print BIGNUM objects, you can print to a FILE pointer using BN_print_<br />

fp( ). It will only print in hexadecimal format, but it does get negative numbers right:<br />

int BN_print_fp(FILE *f, BIGNUM *bn);<br />

Note that you have to supply your own newline if required.<br />

You can also convert a BIGNUM object into a hexadecimal or a base-10 string using one<br />

of the following two functions:<br />

char *BN_bn2hex(BIGNUM *bn);<br />

char *BN_bn2dec(BIGNUM *bn);<br />

You can then do what you like with the string, but note that when it comes time to<br />

deallocate the string, you must call OPENSSL_free( ).<br />

Common tests on BIGNUM objects<br />

The function BN_cmp( ) compares two BIGNUM objects, returning 0 if they’re equal, 1 if<br />

the first one is larger, or –1 if the second one is larger:<br />

int BN_cmp(BIGNUM *a, BIGNUM *b);<br />

The function BN_ucmp( ) is the same as BN_cmp( ), except that it compares the absolute<br />

values of the two numbers:<br />

int BN_ucmp(BIGNUM *a, BIGNUM *b);<br />

The following functions are actually macros that test the value of a single BIGNUM<br />

object, and return 1 or 0 depending on whether the respective condition is true or<br />

false:<br />

BN_is_zero(BIGNUM *bn);<br />

BN_is_one(BIGNUM *bn);<br />

BN_is_odd(BIGNUM *bn);<br />

320 | Chapter 7: Public Key Cryptography<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!