...
Code Block | ||
---|---|---|
| ||
enum {len = 12}; char id[len]; /* id will hold the ID, starting with the characters "ID" */ /* followed by a random integer */ int r; int num; /* ... */ r = rand(); /* generate a random integer */ num = snprintf(id, len, "ID%-d", r); /* generate the ID */ /* ... */ |
...
Compliant Solution (POSIX)
A better pseudorandom number generator is the random()
function.
Code Block | ||
---|---|---|
| ||
enum {len = 12};
char id[len]; /* id will hold the ID, starting with the characters "ID" */
/* followed by a random integer */
int r;
int num;
/* ... */
srandom(time(0)); /* seed the PRNG with the current time */
/* ... */
r = random(); /* generate a random integer */
num = snprintf(id, len, "ID%-d", r); /* generate the ID */
/* ... */
|
However, the instance of the random()
function in this example uses time(0)
as a seed. With a trivial seed like time(0)
, the results from random()
are also predictable.
Compliant Solution (POSIX)
This compliant solution improves the previous non-compliant code example by adding some additional sources of information to the seed.
While the low dozen bits generated by rand()
go through a cyclic pattern, all the bits generated by random()
are usable.
Code Block | ||
---|---|---|
Code Block | ||
| ||
enum {len = 12};
char id[len]; /* id will hold the ID, starting with the characters "ID" */
/* followed by a random integer */
int r;
int num;
/* ... */
srandom(time(0)*getpid()); /* seed the PRNG with the current time */
/* ... */
r = random(); /* generate a random integer */
num = snprintf(id, len, "ID%-d", r); /* generate the ID */
/* ... */
|
...
To achieve the best random numbers possible, an implementation-specific function must be used. When unpredictability really matters and speed is not an issue, such as in the creation of strong cryptographic keys, use a true entropy source such as /dev/random
or a hardware device capable of generating random numbers. Note that the /dev/random
device may block for a long time if there are not enough events going on to generate sufficient entropy.In many cases, however, it will be acceptable to simply use a pseudorandom number generator from a cryptographic library (such as the Mersenne Twister) and seed it with data read from /dev/random
.
Compliant Solution (Windows)
...