//! Trusty implementation of `kmr_common::crypto::Rng`.
use kmr_common::crypto::Rng;
/// [`kmr_common::crypto::Rng`] implementation for Trusty. pubstruct TrustyRng;
impl Rng for TrustyRng { // Safety: No op as intended, BoringSSL's RAND_bytes() doesn't utilize this function. fn add_entropy(&mutself, _data: &[u8]) {}
/// Generate a buffer of size N filled with random bytes. pubfn generate_random_buffer<const N: usize>() -> [u8; N] { letmut rng = TrustyRng; letmut bytes = [0; N];
rng.fill_bytes(&mut bytes);
bytes
}
/// Generate a byte vector of size N filled with random bytes. pubfn generate_random_vec<const N: usize>() -> Vec<u8> { letmut rng = TrustyRng; letmut bytes = vec![0u8; N];
rng.fill_bytes(bytes.as_mut_slice());
bytes
}
/// Generate a random integer of the given type. /// /// This is implemented as a macro because there's no generic way to turn a blob of random bytes /// into a specific type. In fact, even generating a random integer of a specific size is difficult /// because size_of can't be used on generic types in current Rust.
macro_rules! generate_random_int {
($int_type:ty) => {{ const INT_SIZE: usize = std::mem::size_of::<$int_type>(); let bytes = $crate::rng::generate_random_buffer::<INT_SIZE>(); let var = <$int_type>::from_ne_bytes(bytes);
var
}};
} pub(crate) use generate_random_int;
#[cfg(test)] mod test { usesuper::{generate_random_buffer, generate_random_vec}; use std::array;
// These tests all generate random buffers and then compare them, with the expectation that // said buffers should never be equal. This is technically not guaranteed to be true: you could // get two random buffers that just happen to be precisely the same value. // // If that happens to you, then congratulations: you are the unluckiest person in the universe. // But if this is actually failing, the much much more likely outcome is that the rng is // actually broken in some way.
#[test] fn test_random_buffers() { let buf1 = generate_random_buffer::<512>(); let buf2 = generate_random_buffer::<512>();
assert_ne!(buf1, buf2);
}
#[test] fn test_random_vectors() { let vec1 = generate_random_vec::<512>(); let vec2 = generate_random_vec::<512>();
assert_ne!(vec1, vec2);
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.