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.

#define SPC_RC4RNG_UNLOCK( ) ReleaseMutex(hSpcRC4RNGMutex)<br />

#endif<br />

#define SPC_ARBITRARY_SIZE 16<br />

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

static unsigned char zeros[SPC_ARBITRARY_SIZE] = {0,};<br />

unsigned char *p = buf;<br />

#ifdef WIN32<br />

if (!hSpcRC4RNGMutex) hSpcRC4RNGMutex = CreateMutex(0, FALSE, 0);<br />

#endif<br />

SPC_RC4RNG_LOCK( );<br />

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

RC4(&spc_prng, SPC_ARBITRARY_SIZE, zeros, p);<br />

l -= SPC_ARBITRARY_SIZE;<br />

p += SPC_ARBITRARY_SIZE;<br />

}<br />

if (l) RC4(&spc_prng, l, zeros, p);<br />

SPC_RC4RNG_UNLOCK( );<br />

return buf;<br />

}<br />

Note that, although we don’t show it in this code, you should ensure that the generator<br />

is initialized before giving output.<br />

Because using this RC4 API requires encrypting zero bytes to get the keystream output,<br />

in order to be able to generate data of arbitrary sizes, you must either dynamically<br />

allocate and zero out memory every time or iteratively call RC4 in chunks of up<br />

to a fixed size using a static buffer filled with zeros. We opt for the latter approach.<br />

RC4 is only believed to be a strong source of random numbers for<br />

about 2 30 outputs. After that, we strongly recommend that you reseed<br />

it with new entropy. If your application would not conceivably use<br />

that many outputs, it should generally be okay not to check that condition.<br />

Using a generator based on a cryptographic hash function<br />

The most common mistake made when trying to use a hash function as a cryptographic<br />

pseudo-random number generator is to continually hash a piece of data.<br />

Such an approach gives away the generator’s internal state with every output. For<br />

example, suppose that your internal state is some value X, and you generate and output<br />

Y by hashing X. The next time you need random data, rehashing X will give the<br />

same results, and any attacker who knows the last outputs from the generator can<br />

figure out the next outputs if you generate them by hashing Y.<br />

588 | 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!