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.

313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,<br />

419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,<br />

509, 521, 523, 541<br />

};<br />

static int is_obviously_not_prime(BIGNUM *p);<br />

static int passes_rabin_miller_once(BIGNUM *p);<br />

static unsigned int calc_b_and_m(BIGNUM *p, BIGNUM *m);<br />

int spc_is_probably_prime(BIGNUM *p) {<br />

int i;<br />

if (is_obviously_not_prime(p)) return 0;<br />

for (i = 0; i < NUMBER_ITERS; i++)<br />

if (!passes_rabin_miller_once(p))<br />

return 0;<br />

return 1;<br />

}<br />

BIGNUM *spc_generate_prime(int nbits) {<br />

BIGNUM *p = BN_new( );<br />

unsigned char binary_rep[nbits / 8];<br />

/* This code assumes we'll only ever want to generate primes with the number of<br />

* bits a multiple of eight!<br />

*/<br />

if (nbits % 8 || !p) abort( );<br />

for (;;) {<br />

spc_rand(binary_rep, nbits / 8);<br />

/* Set the two most significant and the least significant bits to 1. */<br />

binary_rep[0] |= 0xc0;<br />

binary_rep[nbits / 8 - 1] |= 1;<br />

/* Convert this number to its BIGNUM representation */<br />

if (!BN_bin2bn(binary_rep, nbits / 8, p)) abort( );<br />

/* If you're going to test for suitability as a Diffie-Hellman prime, do so<br />

* before calling spc_is_probably_prime(p).<br />

*/<br />

if (spc_is_probably_prime(p)) return p;<br />

}<br />

}<br />

/* Try simple division with all our small primes. This is, for each prime, if it<br />

* evenly divides p, return 0. Note that this obviously doesn't work if we're<br />

* checking a prime number that's in the list!<br />

*/<br />

static int is_obviously_not_prime(BIGNUM *p) {<br />

int i;<br />

for (i = 0; i < NUMBER_PRIMES; i++)<br />

if (!BN_mod_word(p, primes[i])) return 1;<br />

return 0;<br />

}<br />

Generating a Prime Number (Testing for Primality) | 325<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!