...
Compliant Solution (Linux, Solaris, Mac OS X, NetBSD, OpenBSD)
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 When unpredictability really matters and speed is not an issue, use a true entropy source such as /dev/random
or even a hardware source such as a quantum mirror. In most cases, however, it will be acceptable to simply use a pseudo-random number generator from a cryptographic library (such as a the Mersenne Twister) and seed it with data that are read from /dev/random
.
The /dev/random
device may block for a long time if there are not enough events going on to generate sufficient randomness; entropy.
A read from the
/dev/urandom
...
device will not block
...
waiting for more entropy. As a result, if there is not sufficient entropy in the entropy pool, the returned values are theoretically vulnerable to a cryptographic attack on the algorithms used by the driver. Knowledge of how to do this is not available in the current non-classified literature, but it is theoretically possible that such an attack may exist. If this is a concern in your application, use
/dev/random
instead.
The rand48
family of functions provides another pseudo-random alternative.
...