21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

while (xl-- && i < SPC_BLOCK_SZ)<br />

prng->ctr[i++] = *x++;<br />

prng->ix = 0;<br />

prng->kl = kl;<br />

SPC_BCPRNG_UNLOCK( );<br />

}<br />

unsigned char *spc_bcprng_rand(SPC_BCPRNG_CTX *prng, unsigned char *buf, size_t l) {<br />

unsigned char *p;<br />

SPC_BCPRNG_LOCK( );<br />

for (p = buf; prng->ix && l; l--) {<br />

*p++ = prng->lo[prng->ix++];<br />

prng->ix %= SPC_BLOCK_SZ;<br />

}<br />

while (l >= SPC_BLOCK_SZ) {<br />

SPC_DO_ENCRYPT(&(prng->ks), prng->ctr, p);<br />

spc_increment_counter(prng);<br />

p += SPC_BLOCK_SZ;<br />

l -= SPC_BLOCK_SZ;<br />

}<br />

if (l) {<br />

SPC_DO_ENCRYPT(&(prng->ks), prng->ctr, prng->lo);<br />

spc_increment_counter(prng);<br />

prng->ix = l;<br />

while (l--) p[l] = prng->lo[l];<br />

}<br />

SPC_BCPRNG_UNLOCK( );<br />

return buf;<br />

}<br />

If your block cipher has 64-bit blocks and has no practical weaknesses, do not use<br />

this generator for more than 235 bytes of output (232 block cipher calls). If the cipher<br />

has 128-bit blocks, do not exceed 268 bytes of output (264 block cipher calls). If using<br />

a 128-bit block cipher, it is generally acceptable not to check for this condition, as<br />

you generally would not reasonably expect to ever use that many bytes of output.<br />

To bind this cryptographic PRNG to the API in Recipe 11.2, you can use a single global<br />

generator context that you seed in spc_rand_init( ), requiring you to get a secure<br />

seed. Once that’s done (assuming the generator variable is a statically allocated global<br />

variable named spc_prng), you can simply implement spc_rand( ) as follows:<br />

unsigned char *spc_rand(unsigned char *buf, size_t l) {<br />

return spc_bcprng_rand(&spc_prng, buf, l);<br />

}<br />

Note that you should probably be sure to check that the generator is seeded before<br />

calling spc_bcprng_rand( ).<br />

586 | Chapter 11: Random Numbers<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!