2016-05-19 22:03:04 +00:00
|
|
|
|
2016-08-14 19:59:54 +00:00
|
|
|
/// The single place where we generate random material
|
|
|
|
/// for our own use. These functions never fail,
|
|
|
|
/// they panic on error.
|
2016-05-19 22:03:04 +00:00
|
|
|
|
2017-05-04 19:51:50 +00:00
|
|
|
use ring::rand::{SystemRandom, SecureRandom};
|
2019-01-20 17:24:27 +00:00
|
|
|
use crate::msgs::codec;
|
2016-05-19 22:03:04 +00:00
|
|
|
|
2016-08-14 19:59:54 +00:00
|
|
|
/// Fill the whole slice with random material.
|
2016-05-19 22:03:04 +00:00
|
|
|
pub fn fill_random(bytes: &mut [u8]) {
|
2017-05-04 19:51:50 +00:00
|
|
|
SystemRandom::new()
|
2017-01-03 21:15:21 +00:00
|
|
|
.fill(bytes)
|
|
|
|
.unwrap();
|
2016-05-19 22:03:04 +00:00
|
|
|
}
|
2017-01-10 20:55:17 +00:00
|
|
|
|
2017-12-02 16:30:56 +00:00
|
|
|
/// Make a Vec<u8> of the given size
|
|
|
|
/// containing random material.
|
|
|
|
pub fn random_vec(len: usize) -> Vec<u8> {
|
2019-05-07 19:08:19 +00:00
|
|
|
let mut v = vec![0; len];
|
2017-12-02 16:30:56 +00:00
|
|
|
fill_random(&mut v);
|
|
|
|
v
|
|
|
|
}
|
|
|
|
|
2017-02-15 00:20:28 +00:00
|
|
|
/// Return a uniformly random u32.
|
2017-01-10 20:55:17 +00:00
|
|
|
pub fn random_u32() -> u32 {
|
|
|
|
let mut buf = [0u8; 4];
|
|
|
|
fill_random(&mut buf);
|
|
|
|
codec::decode_u32(&buf)
|
|
|
|
.unwrap()
|
|
|
|
}
|