[−][src]Struct rand::rngs::JitterRng
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 103..106 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.
JitterRng
can be used without the standard library, but not conveniently,
you must provide a high-precision timer and carefully have to follow the
instructions of new_with_timer
.
This implementation is based on Jitterentropy version 2.1.0.
Note: There is no accurate timer available on Wasm platforms, to help
prevent fingerprinting or timing side-channel attacks. Therefore
JitterRng::new()
is not available on Wasm.
Quality testing
JitterRng::new()
has build-in, but limited, quality testing, however
before using JitterRng
on untested hardware, or after changes that could
effect how the code is optimized (such as a new LLVM version), it is
recommend to run the much more stringent
NIST SP 800-90B Entropy Estimation Suite.
Use the following code using timer_stats
to collect the data:
use rand::jitter::JitterRng; let mut rng = JitterRng::new()?; // 1_000_000 results are required for the // NIST SP 800-90B Entropy Estimation Suite const ROUNDS: usize = 1_000_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)?;
This will produce two files: jitter_rng_var.bin
and jitter_rng_min.bin
.
Run the Entropy Estimation Suite in three configurations, as outlined below.
Every run has two steps. One step to produce an estimation, another to
validate the estimation.
- Estimate the expected amount of entropy that is at least available with
each round of the entropy collector. This number should be greater than
the amount estimated with
64 / test_timer()
.python noniid_main.py -v jitter_rng_var.bin 8 restart.py -v jitter_rng_var.bin 8 <min-entropy>
- Estimate 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.python noniid_main.py -v -u 4 jitter_rng_var.bin 4 restart.py -v -u 4 jitter_rng_var.bin 4 <min-entropy>
- Estimate the expected amount of entropy that is available to the entropy
collector 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.
python noniid_main.py -v -u 4 jitter_rng_min.bin 4 restart.py -v -u 4 jitter_rng_min.bin 4 <min-entropy>
Methods
impl JitterRng
[src]
impl JitterRng
pub fn new() -> Result<JitterRng, TimerError>
[src]
pub fn new() -> Result<JitterRng, TimerError>
Create a new JitterRng
. Makes use of std::time
for a timer, or a
platform-specific function with higher accuracy if necessary and
available.
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.
pub fn new_with_timer(timer: fn() -> u64) -> JitterRng
[src]
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
. Also it is important to
consume at least one u64
before using the first result to initialize
the entropy collection pool.
Example
use rand::jitter::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 } let mut rng = JitterRng::new_with_timer(get_nstime); let rounds = rng.test_timer()?; rng.set_rounds(rounds); // optional let _ = rng.gen::<u64>(); // Ready for use let v: u64 = rng.gen();
pub fn set_rounds(&mut self, rounds: u8)
[src]
pub fn set_rounds(&mut self, rounds: u8)
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.
pub fn test_timer(&mut self) -> Result<u8, TimerError>
[src]
pub fn test_timer(&mut self) -> Result<u8, 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.
pub fn timer_stats(&mut self, var_rounds: bool) -> i64
[src]
pub fn timer_stats(&mut self, var_rounds: bool) -> i64
Statistical test: return the timer delta of one normal run of the
JitterRng
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
JitterRng
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 the entropy collector can collect in the worst
case.
See Quality testing on how to
use timer_stats
to test the quality of JitterRng
.
Trait Implementations
impl Clone for JitterRng
[src]
impl Clone for JitterRng
fn clone(&self) -> JitterRng
[src]
fn clone(&self) -> JitterRng
Returns a copy of the value. Read more
fn clone_from(&mut self, source: &Self)
1.0.0[src]
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read more
impl Debug for JitterRng
[src]
impl Debug for JitterRng
fn fmt(&self, f: &mut Formatter) -> Result
[src]
fn fmt(&self, f: &mut Formatter) -> Result
Formats the value using the given formatter. Read more
impl RngCore for JitterRng
[src]
impl RngCore for JitterRng
fn next_u32(&mut self) -> u32
[src]
fn next_u32(&mut self) -> u32
Return the next random u32
. Read more
fn next_u64(&mut self) -> u64
[src]
fn next_u64(&mut self) -> u64
Return the next random u64
. Read more
fn fill_bytes(&mut self, dest: &mut [u8])
[src]
fn fill_bytes(&mut self, dest: &mut [u8])
Fill dest
with random data. Read more
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>
[src]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>
Fill dest
entirely with random data. Read more
impl CryptoRng for JitterRng
[src]
impl CryptoRng for JitterRng
Auto Trait Implementations
Blanket Implementations
impl<R> Rng for R where
R: RngCore + ?Sized,
[src]
impl<R> Rng for R where
R: RngCore + ?Sized,
fn gen<T>(&mut self) -> T where
Standard: Distribution<T>,
[src]
fn gen<T>(&mut self) -> T where
Standard: Distribution<T>,
Return a random value supporting the [Standard
] distribution. Read more
fn gen_range<T: PartialOrd + SampleUniform>(&mut self, low: T, high: T) -> T
[src]
fn gen_range<T: PartialOrd + SampleUniform>(&mut self, low: T, high: T) -> T
Generate a random value in the range [low
, high
), i.e. inclusive of low
and exclusive of high
. Read more
fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T
[src]
fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T
Sample a new value, using the given distribution. Read more
ⓘImportant traits for DistIter<'a, D, R, T>fn sample_iter<'a, T, D: Distribution<T>>(
&'a mut self,
distr: &'a D
) -> DistIter<'a, D, Self, T> where
Self: Sized,
[src]
fn sample_iter<'a, T, D: Distribution<T>>(
&'a mut self,
distr: &'a D
) -> DistIter<'a, D, Self, T> where
Self: Sized,
Create an iterator that generates values using the given distribution. Read more
fn fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T)
[src]
fn fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T)
Fill dest
entirely with random bytes (uniform value distribution), where dest
is any type supporting [AsByteSliceMut
], namely slices and arrays over primitive integer types (i8
, i16
, u32
, etc.). Read more
fn try_fill<T: AsByteSliceMut + ?Sized>(
&mut self,
dest: &mut T
) -> Result<(), Error>
[src]
fn try_fill<T: AsByteSliceMut + ?Sized>(
&mut self,
dest: &mut T
) -> Result<(), Error>
Fill dest
entirely with random bytes (uniform value distribution), where dest
is any type supporting [AsByteSliceMut
], namely slices and arrays over primitive integer types (i8
, i16
, u32
, etc.). Read more
fn gen_bool(&mut self, p: f64) -> bool
[src]
fn gen_bool(&mut self, p: f64) -> bool
Return a bool with a probability p
of being true. Read more
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T>
[src]
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T>
Return a random element from values
. Read more
fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T>
[src]
fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T>
Return a mutable pointer to a random element from values
. Read more
fn shuffle<T>(&mut self, values: &mut [T])
[src]
fn shuffle<T>(&mut self, values: &mut [T])
Shuffle a mutable slice in place. Read more
ⓘImportant traits for Generator<T, R>fn gen_iter<T>(&mut self) -> Generator<T, &mut Self> where
Standard: Distribution<T>,
[src]
fn gen_iter<T>(&mut self) -> Generator<T, &mut Self> where
Standard: Distribution<T>,
: use Rng::sample_iter(&Standard) instead
Return an iterator that will yield an infinite number of randomly generated items. Read more
fn gen_weighted_bool(&mut self, n: u32) -> bool
[src]
fn gen_weighted_bool(&mut self, n: u32) -> bool
: use gen_bool instead
Return a bool with a 1 in n chance of true Read more
ⓘImportant traits for AsciiGenerator<R>fn gen_ascii_chars(&mut self) -> AsciiGenerator<&mut Self>
[src]
fn gen_ascii_chars(&mut self) -> AsciiGenerator<&mut Self>
: use sample_iter(&Alphanumeric) instead
Return an iterator of random characters from the set A-Z,a-z,0-9. Read more
impl<T, U> Into for T where
U: From<T>,
[src]
impl<T, U> Into for T where
U: From<T>,
impl<T> ToOwned for T where
T: Clone,
[src]
impl<T> ToOwned for T where
T: Clone,
type Owned = T
fn to_owned(&self) -> T
[src]
fn to_owned(&self) -> T
Creates owned data from borrowed data, usually by cloning. Read more
fn clone_into(&self, target: &mut T)
[src]
fn clone_into(&self, target: &mut T)
🔬 This is a nightly-only experimental API. (toowned_clone_into
)
recently added
Uses borrowed data to replace owned data, usually by cloning. Read more
impl<T> From for T
[src]
impl<T> From for T
impl<T, U> TryFrom for T where
T: From<U>,
[src]
impl<T, U> TryFrom for T where
T: From<U>,
type Error = !
try_from
)The type returned in the event of a conversion error.
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
try_from
)Performs the conversion.
impl<T> Borrow for T where
T: ?Sized,
[src]
impl<T> Borrow for T where
T: ?Sized,
impl<T> BorrowMut for T where
T: ?Sized,
[src]
impl<T> BorrowMut for T where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
[src]
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
impl<T, U> TryInto for T where
U: TryFrom<T>,
[src]
impl<T, U> TryInto for T where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
try_from
)The type returned in the event of a conversion error.
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
try_from
)Performs the conversion.
impl<T> Any for T where
T: 'static + ?Sized,
[src]
impl<T> Any for T where
T: 'static + ?Sized,
fn get_type_id(&self) -> TypeId
[src]
fn get_type_id(&self) -> TypeId
🔬 This is a nightly-only experimental API. (get_type_id
)
this method will likely be replaced by an associated static
Gets the TypeId
of self
. Read more