JitterRng

Struct JitterRng 

Source
pub struct JitterRng { /* private fields */ }
Expand description

A true random number generator based on jitter in the CPU execution time, and jitter in memory access time.

This is a true random number generator, as opposed to pseudo-random generators. Random numbers generated by JitterRng can be seen as fresh entropy. A consequence is that is orders of magnitude slower than OsRng and PRNGs (about 10^3 .. 10^6 slower).

There are very few situations where using this RNG is appropriate. Only very few applications require true entropy. A normal PRNG can be statistically indistinguishable, and a cryptographic PRNG should also be as impossible to predict.

Use of JitterRng is recommended for initializing cryptographic PRNGs when OsRng is not available.

This implementation is based on Jitterentropy version 2.1.0.

Implementations§

Source§

impl JitterRng

Source

pub fn new() -> Result<JitterRng, TimerError>

Create a new JitterRng. Makes use of std::time for a timer.

During initialization CPU execution timing jitter is measured a few hundred times. If this does not pass basic quality tests, an error is returned. The test result is cached to make subsequent calls faster.

Source

pub fn new_with_timer(timer: fn() -> u64) -> JitterRng

Create a new JitterRng. A custom timer can be supplied, making it possible to use JitterRng in no_std environments.

The timer must have nanosecond precision.

This method is more low-level than new(). It is the responsibility of the caller to run test_timer before using any numbers generated with JitterRng, and optionally call set_rounds().

Source

pub fn set_rounds(&mut self, rounds: u32)

Configures how many rounds are used to generate each 64-bit value. This must be greater than zero, and has a big impact on performance and output quality.

new_with_timer conservatively uses 64 rounds, but often less rounds can be used. The test_timer() function returns the minimum number of rounds required for full strength (platform dependent), so one may use rng.set_rounds(rng.test_timer()?); or cache the value.

Source

pub fn test_timer(&mut self) -> Result<u32, TimerError>

Basic quality tests on the timer, by measuring CPU timing jitter a few hundred times.

If succesful, this will return the estimated number of rounds necessary to collect 64 bits of entropy. Otherwise a TimerError with the cause of the failure will be returned.

Source

pub fn timer_stats(&mut self, var_rounds: bool) -> i64

Statistical test: return the timer delta of one normal run of the JitterEntropy entropy collector.

Setting var_rounds to true will execute the memory access and the CPU jitter noice sources a variable amount of times (just like a real JitterEntropy round).

Setting var_rounds to false will execute the noice sources the minimal number of times. This can be used to measure the minimum amount of entropy one round of entropy collector can collect in the worst case.

§Example

Use timer_stats to run the [NIST SP 800-90B Entropy Estimation Suite] (https://github.com/usnistgov/SP800-90B_EntropyAssessment).

This is the recommended way to test the quality of JitterRng. It should be run before using the RNG on untested hardware, after changes that could effect how the code is optimised, and after major compiler compiler changes, like a new LLVM version.

First generate two files jitter_rng_var.bin and jitter_rng_var.min.

Execute python noniid_main.py -v jitter_rng_var.bin 8, and validate it with restart.py -v jitter_rng_var.bin 8 <min-entropy>. This number is the expected amount of entropy that is at least available for each round of the entropy collector. This number should be greater than the amount estimated with 64 / test_timer().

Execute python noniid_main.py -v -u 4 jitter_rng_var.bin 4, and validate it with restart.py -v -u 4 jitter_rng_var.bin 4 <min-entropy>. This number is the expected amount of entropy that is available in the last 4 bits of the timer delta after running noice sources. Note that a value of 3.70 is the minimum estimated entropy for true randomness.

Execute python noniid_main.py -v -u 4 jitter_rng_var.bin 4, and validate it with restart.py -v -u 4 jitter_rng_var.bin 4 <min-entropy>. This number is the expected amount of entropy that is available to the entropy collecter if both noice sources only run their minimal number of times. This measures the absolute worst-case, and gives a lower bound for the available entropy.

use rand::JitterRng;

fn get_nstime() -> u64 {
    use std::time::{SystemTime, UNIX_EPOCH};

    let dur = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
    // The correct way to calculate the current time is
    // `dur.as_secs() * 1_000_000_000 + dur.subsec_nanos() as u64`
    // But this is faster, and the difference in terms of entropy is
    // negligible (log2(10^9) == 29.9).
    dur.as_secs() << 30 | dur.subsec_nanos() as u64
}

// Do not initialize with `JitterRng::new`, but with `new_with_timer`.
// 'new' always runst `test_timer`, and can therefore fail to
// initialize. We want to be able to get the statistics even when the
// timer test fails.
let mut rng = JitterRng::new_with_timer(get_nstime);

// 1_000_000 results are required for the NIST SP 800-90B Entropy
// Estimation Suite
// FIXME: this number is smaller here, otherwise the Doc-test is too slow
const ROUNDS: usize = 10_000;
let mut deltas_variable: Vec<u8> = Vec::with_capacity(ROUNDS);
let mut deltas_minimal: Vec<u8> = Vec::with_capacity(ROUNDS);

for _ in 0..ROUNDS {
    deltas_variable.push(rng.timer_stats(true) as u8);
    deltas_minimal.push(rng.timer_stats(false) as u8);
}

// Write out after the statistics collection loop, to not disturb the
// test results.
File::create("jitter_rng_var.bin")?.write(&deltas_variable)?;
File::create("jitter_rng_min.bin")?.write(&deltas_minimal)?;

Trait Implementations§

Source§

impl Debug for JitterRng

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Rng for JitterRng

Source§

fn next_u32(&mut self) -> u32

Return the next random u32. Read more
Source§

fn next_u64(&mut self) -> u64

Return the next random u64. Read more
Source§

fn fill_bytes(&mut self, dest: &mut [u8])

Fill dest with random data. Read more
Source§

fn next_f32(&mut self) -> f32

Return the next random f32 selected from the half-open interval [0, 1). Read more
Source§

fn next_f64(&mut self) -> f64

Return the next random f64 selected from the half-open interval [0, 1). Read more
Source§

fn gen<T>(&mut self) -> T
where T: Rand, Self: Sized,

Return a random value of a Rand type. Read more
Source§

fn gen_iter<'a, T>(&'a mut self) -> Generator<'a, T, Self>
where T: Rand, Self: Sized,

Return an iterator that will yield an infinite number of randomly generated items. Read more
Source§

fn gen_range<T>(&mut self, low: T, high: T) -> T
where T: PartialOrd + SampleRange, Self: Sized,

Generate a random value in the range [low, high). Read more
Source§

fn gen_weighted_bool(&mut self, n: u32) -> bool
where Self: Sized,

Return a bool with a 1 in n chance of true Read more
Source§

fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self>
where Self: Sized,

Return an iterator of random characters from the set A-Z,a-z,0-9. Read more
Source§

fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T>
where Self: Sized,

Return a random element from values. Read more
Source§

fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T>
where Self: Sized,

Return a mutable pointer to a random element from values. Read more
Source§

fn shuffle<T>(&mut self, values: &mut [T])
where Self: Sized,

Shuffle a mutable slice in place. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Erased for T