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.

See Also<br />

Recipes 11.16, 11.18, 11.19<br />

11.2 Using a Generic API for Randomness and<br />

Entropy<br />

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

You would like to have a standard API for getting cryptographic randomness or<br />

entropy, which you can then bind to any underlying implementation. Many recipes<br />

in this book rely on random numbers and use the API in this recipe without concern<br />

for what implementation is behind it.<br />

Solution<br />

The API in this recipe is exactly what you need. In this recipe, we show the API and<br />

how to use it. In the next few recipes, we discuss how to bind it to third-party randomness<br />

infrastructures.<br />

Discussion<br />

At an API level, this recipe is only going to look at how to fill a buffer with random<br />

bytes. To get random values for other data types, see Recipes 11.10 through 11.14.<br />

Here we are going to build a random number generation API where there is only a<br />

single generator per application, or perhaps even a single generator for the entire<br />

machine. Either way, we expect that the application will have to initialize the API.<br />

Note that the initialization may need to seed a cryptographic pseudo-random number<br />

generator, so the initialization part might hang. If that is a problem, launch a<br />

thread to call the initialization routine, but be aware that asking for any cryptographically<br />

strong pseudo-random numbers at all will cause your program to abort if the<br />

system has not been initialized. The initialization routine is simply:<br />

void spc_rand_init(void);<br />

Because we know well that people will often forget to perform initialization, implementations<br />

of this API should automatically check to see if this routine has been<br />

called when using other API calls, and call it at that point if not.<br />

After initialization, we will provide two universally available options for reading<br />

data, as well as a third option that will not always be available:<br />

• Get cryptographically strong random numbers, as generated from a well-seeded<br />

pseudo-random number generator.<br />

Using a Generic API for Randomness and Entropy | 573<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!