1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
pub use crypto_api;
use crypto_api::rng::SecureRng;
use std::{
error::Error,
fmt::{ Display, Formatter, Result as FmtResult }
};
#[derive(Debug, Eq, PartialEq, Copy, Clone)]
pub struct OsRandomError;
impl Display for OsRandomError {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{:?}", self)
}
}
impl Error for OsRandomError {}
pub struct OsRandom;
impl OsRandom {
pub fn secure_rng() -> Box<dyn SecureRng> {
Box::new(Self)
}
}
impl SecureRng for OsRandom {
fn random(&mut self, buf: &mut[u8]) -> Result<(), Box<dyn Error + 'static>> {
extern "C" {
fn crypto_api_osrandom_secrandom(buf: *mut u8, len: usize) -> u8;
}
Ok(match unsafe{ crypto_api_osrandom_secrandom(buf.as_mut_ptr(), buf.len()) } {
0 => (),
_ => Err(OsRandomError)?
})
}
}