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.

11.4 Using the Standard Windows Randomness<br />

Infrastructure<br />

<strong>Problem</strong><br />

You want to use random numbers on a Windows system.<br />

Solution<br />

Use CryptGenRandom( ) unless you absolutely need entropy, in which case see Recipe<br />

11.8 and Recipes 11.20 through 11.23.<br />

Discussion<br />

Microsoft allows you to get cryptographically strong pseudo-random numbers using<br />

the CryptoAPI function CryptGenRandom( ). Unfortunately, there is no provision for<br />

any way to get entropy. The system does collect entropy behind the scenes, which it<br />

uses to improve the quality of the cryptographically strong pseudo-random numbers<br />

it gets.<br />

Therefore, if this interface is being used to bind to the API we describe in Recipe<br />

11.2, we can only implement spc_rand( ) and spc_keygen( ), both of which will be<br />

exactly the same. If you want to try to get actual entropy on Windows, the only<br />

solution as of this writing is to use EGADS, which we discuss in Recipe 11.8. Alternatively,<br />

you can collect it yourself, as discussed in Recipes 11.20 through 11.23.<br />

To use CryptGenRand( ), you must first acquire an HCRYPTPROV context. To do this, use<br />

the function CryptAcquireContext( ), which we discuss in some detail in Recipe 5.25.<br />

With an HCRYPTPROV context in hand, you can call CryptGenRandom( ), which will<br />

return TRUE if it is successful; otherwise, it will return FALSE, but it should never fail.<br />

CryptGenRandom( ) has the following signature:<br />

BOOL CryptGenRandom(HCRYPTPROV *hProv, DWORD dwLen, BYTE *pbBuffer);<br />

This function has the following arguments:<br />

hProv<br />

Handle to a cryptographic service provider obtained via CryptAcquireContext( ).<br />

dwLen<br />

Number of bytes of random data required. The output buffer must be at least<br />

this large.<br />

pbBuffer<br />

Buffer into which the random data will be written.<br />

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