Expand description
§Random Number Generator (RNG)
§Overview
The Random Number Generator (RNG) module provides an interface to generate random numbers using the RNG peripheral on ESP chips. This driver allows you to generate random numbers that can be used for various cryptographic, security, or general-purpose applications.
There are certain pre-conditions which must be met in order for the RNG to
produce true random numbers.
For more details see Trng.
The hardware RNG produces true random numbers
under any of the following conditions:
- RF subsystem is enabled (i.e. Wi-Fi or Bluetooth are enabled).
- An ADC is used to generate entropy.
When any of these conditions are true, samples of physical noise are
continuously mixed into the internal hardware RNG state to provide entropy.
If none of the above conditions are true, the output of the RNG should be
considered pseudo-random only. See Rng.
For more information, please refer to the ESP-IDF documentation.
§Example
let rng = Rng::new();
// Generate a random word (u32):
let rand_word = rng.random();
// Fill a buffer with random bytes:
let mut buf = [0u8; 16];
rng.read(&mut buf);
loop {}§Compatibility with getrandom
The driver can be used directly, or integrated as a custom backend
for getrandom (e.g. v0.4):
#[unsafe(no_mangle)]
unsafe extern "Rust" fn __getrandom_v04_custom(
dest: *mut u8,
len: usize,
) -> Result<(), Error> {
unsafe { esp_hal::rng::Rng::new().read_into_raw(dest, len) };
Ok(())Structs§
- Rng
- (Pseudo-)Random Number Generator.
- Trng
unstable - True Random Number Generator (TRNG)
- Trng
Source unstable - Ensures random numbers are cryptographically secure.