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.

Additionally, you can ask for a random number with a specific number of bits:<br />

int BN_rand(BIGNUM *result, int bits, int top, int bottom);<br />

This function has the following arguments:<br />

result<br />

The generated random number will be stored in this BIGNUM object.<br />

bits<br />

Number of bits that the generated random number should contain.<br />

top<br />

If the value of this argument is 0, the most significant bit in the generated random<br />

number will be set. If it is –1, the most significant bit can be anything. If it<br />

is 1, the 2 most significant bits will be set. This is useful when you want to make<br />

sure that the product of 2 numbers of a particular bit length will always have<br />

exactly twice as many bits.<br />

bottom<br />

If the value of this argument is 1, the resulting random number will be odd. Otherwise,<br />

it may be either odd or even.<br />

Outputting BIGNUM objects<br />

If you wish to represent your BIGNUM object as a binary number, you can use BN_<br />

bn2bin( ), which will store the binary representation of the BIGNUM object in the buffer<br />

pointed to by the outbuf argument:<br />

int BN_bn2bin(BIGNUM *bn, unsigned char *outbuf);<br />

Unfortunately, you first need to know in advance how big the output buffer needs to<br />

be. You can learn this by calling BN_num_bytes( ), which has the following signature:<br />

int BN_num_bytes(BIGNUM *bn);<br />

BN_bn2bin( ) will not output the sign of a number. You can manually<br />

query the sign of the number by using the following macro:<br />

#define BN_is_negative(x) ((x)->neg)<br />

The following is a wrapper that converts a BIGNUM object to binary, allocating its<br />

result via malloc( ) and properly setting the most significant bit to 1 if the result is<br />

negative. Note that you have to pass in a pointer to an unsigned integer. That integer<br />

gets filled with the size of the returned buffer in bytes.<br />

#include <br />

#include <br />

#define BN_is_negative(x) ((x)->neg)<br />

unsigned char *BN_to_binary(BIGNUM *b, unsigned int *outsz) {<br />

unsigned char *ret;<br />

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

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.<br />

Manipulating Big Numbers | 319

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

Saved successfully!

Ooh no, something went wrong!