...
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 */ /* ... */ |
Non-Compliant
...
Code Example (BSD)
A better pseudo random number generator is the BSD function random()
.
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 */ /* ... */ |
The example then uses the BSD function random() function and uses time(0)
as seed. With a trivial seed like time(0)
, however, the results from rand() or random() are equally predictable.
Compliant Solution (UNIX)
To generate an unpredictable number, use an unpredictable seed and a cryptographically strong mixing function. On Unix systems, for example, decent results can be obtained by reading /dev/urandom
, which will not block the application.
When unpredictability really matters (session IDs and crypto keys) use a cryptographical library and seed it with data that are read from /dev/random
.
The rand48
family of functions provides another alternative.
...