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.

double spc_rand_cunifvariate(double mean, double arc) {<br />

return (mean + arc * (spc_rand_real( ) - 0.5)) / SPC_PI;<br />

}<br />

See Also<br />

Recipe 11.12<br />

11.14 Getting a Random Printable ASCII String<br />

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

You want to get a random printable ASCII string.<br />

Solution<br />

If you do not want whitespace characters, the printable ASCII characters have values<br />

from 33 to 126, inclusive. Simply get a random number in that range for each character.<br />

If you want to choose from a different character set (such as the base64 character<br />

set), map each character to a specific numeric value between 0 and the number of<br />

characters you have. Select a random number in that range, and map the number<br />

back to the corresponding character.<br />

Discussion<br />

The code presented in this section returns a random ASCII string of a specified<br />

length, where the specified length includes a terminating NULL byte. We use the printable<br />

ASCII characters, meaning that we never output whitespace or control characters.<br />

Assuming a good underlying infrastructure for randomness, each character should be<br />

equally likely. However, the ease with which an attacker can guess a single random<br />

string is related not only to the entropy in the generator, but also to the length of the<br />

output. If you use a single character, there are only 94 possible values, and a guess<br />

will be right with a probability of 1/94 (not having entropy can give the attacker an<br />

even greater advantage).<br />

As a result, your random strings should use no fewer than 10 random characters (not<br />

including the terminating NULL byte), which gives you about 54 bits of security. For a<br />

more conservative security margin, you should go for 15 to 20 characters.<br />

#include <br />

char *spc_rand_ascii(char *buf, size_t len) {<br />

Getting a Random Printable ASCII String | 611<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!