pub trait SecureGenerator: Generator {
// Required method
fn fill_bytes(&mut self, dst: &mut [u8]);
// Provided methods
unsafe fn fill_raw<T>(&mut self, dst: &mut [T]) { ... }
fn text<E: Encoder>(&mut self, len: usize) -> String { ... }
}Expand description
Trait for RNGs that provide cryptographically secure data.
Required Methods§
Sourcefn fill_bytes(&mut self, dst: &mut [u8])
fn fill_bytes(&mut self, dst: &mut [u8])
Fills dst with random data, which is safe to be used in cryptographic contexts.
§Examples
use ya_rand::*;
let mut rng = new_rng_secure();
let mut data = [0; 1738];
rng.fill_bytes(&mut data);
assert!(data.into_iter().any(|v| v != 0));Provided Methods§
Sourceunsafe fn fill_raw<T>(&mut self, dst: &mut [T])
unsafe fn fill_raw<T>(&mut self, dst: &mut [T])
Fills dst with random data, which is safe to be used in cryptographic contexts.
Differs from SecureGenerator::fill_bytes in that the underlying type of dst
doesn’t need to be a specific type (see safety comment).
§Examples
use ya_rand::*;
#[repr(C)]
#[derive(Clone, Copy, Default, PartialEq, Eq)]
struct NotAByte {
x: u16,
y: u32,
z: u64,
}
let mut rng = new_rng_secure();
let zero_value = NotAByte::default();
let mut data = [zero_value; 69];
unsafe {
rng.fill_raw(&mut data);
}
assert!(data.into_iter().any(|v| v != zero_value));§Safety
T must be valid as nothing more than a collection of bytes.
Integer types are the simplest example of this, but structs of integer
types generally should fall under the same umbrella.
Sourcefn text<E: Encoder>(&mut self, len: usize) -> String
fn text<E: Encoder>(&mut self, len: usize) -> String
Generates a random String with length len, using the provided
Encoder to determine character set and minimum secure length. Because
character sets can only contain valid ascii values, the length of the created
String reprensents both the size of the String in bytes, and the
amount of characters it contains.
Values of len which are less than what would be considered secure for the
Encoder being used will be silently promoted to the minimum secure length.
All provided encoders are accessible via crate::encoding.
Users wishing to implement their own encoding scheme must do so
through the Encoder trait.
Originally inspired by golang’s addition of rand.Text in release 1.24,
but altered to be encoding/length generic and unbiased for non-trivial bases.
§Examples
use ya_rand::*;
use ya_rand::encoding::Base16;
const LEN: usize = 420;
let mut rng = new_rng_secure();
let hex_string = rng.text::<Base16>(LEN);
assert!(hex_string.len() == LEN);
assert!(hex_string.bytes().count() == LEN);
assert!(hex_string.chars().count() == LEN);
for c in hex_string.bytes() {
assert!(
(b'0' <= c && c <= b'9') ||
(b'A' <= c && c <= b'F')
);
}Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.