unstable
only.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. 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 internal entropy source has been enabled by calling
bootloader_random_enable()
and not yet disabled by callingbootloader_random_disable()
. - While the ESP-IDF Second stage bootloader is running. This is because the
default ESP-IDF bootloader implementation calls
bootloader_random_enable()
when the bootloader starts, andbootloader_random_disable()
before executing the app.
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.
For more information, please refer to the ESP-IDF documentation
§Configuration
To use the Rng Driver, you need to initialize it with the RNG peripheral.
Once initialized, you can generate random numbers by calling the random
method, which returns a 32-bit unsigned integer.
§Usage
The driver implements the traits from the rand_core
crate.
§Examples
§Basic RNG operation
let mut rng = Rng::new(peripherals.RNG);
// 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 {}
§TRNG operation
let mut buf = [0u8; 16];
// ADC is not available from now
let mut trng = Trng::new(peripherals.RNG, &mut peripherals.ADC1);
trng.read(&mut buf);
let mut true_rand = trng.random();
let mut rng = trng.downgrade();
// ADC is available now
let analog_pin = peripherals.GPIO32;
let mut adc1_config = AdcConfig::new();
let mut adc1_pin = adc1_config.enable_pin(
analog_pin,
Attenuation::_11dB
);
let mut adc1 = Adc::<ADC1>::new(peripherals.ADC1, adc1_config);
let pin_value: u16 = nb::block!(adc1.read_oneshot(&mut adc1_pin)).unwrap();
rng.read(&mut buf);
true_rand = rng.random();
let pin_value: u16 = nb::block!(adc1.read_oneshot(&mut adc1_pin)).unwrap();
Structs§
- Random number generator driver
- True Random Number Generator (TRNG) driver