Interface to the random number generator of the operating system.
OsRng is the preferred external source of entropy for most applications.
Commonly it is used to initialize a user-space RNG, which can then be used
to generate random values with much less overhead than
OsRng::new() is guaranteed to be very cheap (after the first successful
call), and will never consume more than one file handle per process.
use rand_os::OsRng; use rand_os::rand_core::RngCore; let mut os_rng = OsRng::new().unwrap(); let mut key = [0u8; 16]; os_rng.fill_bytes(&mut key); let random_u64 = os_rng.next_u64();
|Linux, Android|| |
|macOS, iOS|| |
|OpenBSD, Bitrig|| |
|Dragonfly BSD|| |
|Solaris, illumos|| |
|Fuchsia OS|| |
|Web browsers|| |
Rand doesn't have a blanket implementation for all Unix-like operating
systems that reads from
/dev/urandom. This ensures all supported operating
systems are using the recommended interface and respect maximum buffer
The three Emscripten targets
Emscripten's emulation of
/dev/random on web browsers and Node.js.
The bare WASM target
methods directly, using either
wasm-bindgen depending on what
features are activated for this crate. Note that if both features are
wasm-bindgen will be used.
It is possible that early in the boot process the OS hasn't had enough time yet to collect entropy to securely seed its RNG, especially on virtual machines.
Some operating systems always block the thread until the RNG is securely seeded. This can take anywhere from a few seconds to more than a minute. Others make a best effort to use a seed from before the shutdown and don't document much.
A few, Linux, NetBSD and Solaris, offer a choice between blocking, and
getting an error. With
try_fill_bytes we choose to get the error
ErrorKind::NotReady), while the other methods use a blocking interface.
On Linux (when the
genrandom system call is not available) and on NetBSD
/dev/urandom never blocks, even when the OS hasn't collected
enough entropy yet. As a countermeasure we try to do a single read from
/dev/random until we know the OS RNG is initialized (and store this in a
We cannot guarantee that
OsRng will fail, but if it does, it will likely
be either when
OsRng::new() is first called or when data is first read.
If you wish to catch errors early, then test reading of at least one byte
try_fill_bytes. If this succeeds, it is extremely
unlikely that any further errors will occur.
A random number generator that retrieves randomness straight from the operating system.