BDE 4.14.0 Production release
|
Provide a common interface to a system's random number generator.
This component provides a namespace, bdlb::RandomDevice
, for a suite of functions used to generate random seeds from platform-dependent random number generators. Two variants are provided: one which may block, but which potentially samples from a stronger distribution, and another which does not block, but which potentially should not be used for cryptography. The strength of these random numbers and the performance of these calls is strongly dependent on the underlying system. On UNIX-like platforms getRandomBytes()
reads from /dev/random
and getRandomBytesNonBlocking()
reads from /dev/urandom
. On Windows both methods use CryptGenRandom
.
Note that (at least on UNIX-like systems) it is not appropriate to call these functions repeatedly to generate many random numbers. A call to getRandomBytes()
can block if available entropy is exhausted, and both getRandomBytes()
and getRandomBytesNonBlocking()
open and close their respective devices on each call. Instead, these functions should be used for seeding pseudo-random random number generators. (E.g., promiscuous use of getRandomBytes()
appears to have caused the WP in {DRQS 92851043}
.)
There is discussion about which of /dev/random
or /dev/urandom
is best, especially on modern Linux systems, while man
pages on other UNIX systems continue to make claims about /dev/random
providing "more secure" numbers than /dev/urandom
. See {http://www.2uo.de/myths-about-urandom/}
, for example. This component deliberately takes no stand on the issue, making both available and leaving it for users to decide which to use.
This section illustrates intended use of this component.
System-provided random-number generators generally must be initialized with a seed value from which they go on to produce their stream of pseudo-random numbers. We can use RandomDevice
to provide such a seed.
First, we obtain the results of invoking the random-number generator without having seeded it:
Then, we obtain a random number:
Next, we seed the random-number generator with our seed:
Finally, we observe that we obtain different numbers: