use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use rand::Rng;
use subtle::ConstantTimeEq;
pub fn random_bytes(length: usize) -> Vec<u8> {
let mut buf = vec![0u8; length];
UnwrapErr(SysRng).fill_bytes(&mut buf);
buf
}
pub(crate) fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
a.ct_eq(b).into()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn produces_correct_length() {
for len in [0, 1, 8, 16, 32, 64, 255] {
let bytes = random_bytes(len);
assert_eq!(bytes.len(), len, "Expected {len} bytes");
}
}
#[test]
fn zero_length_returns_empty() {
let bytes = random_bytes(0);
assert!(bytes.is_empty());
}
#[test]
fn not_all_zeros_for_reasonable_length() {
let bytes = random_bytes(32);
assert!(
bytes.iter().any(|&b| b != 0),
"32 random bytes were all zero – RNG may be broken"
);
}
#[test]
fn consecutive_calls_differ() {
let a = random_bytes(16);
let b = random_bytes(16);
assert_ne!(
a, b,
"Two consecutive 16-byte draws were identical – RNG may be broken"
);
}
#[test]
fn large_buffer() {
let bytes = random_bytes(4096);
assert_eq!(bytes.len(), 4096);
}
#[test]
fn constant_time_eq_equal_slices() {
assert!(constant_time_eq(&[0x01, 0x02, 0x03], &[0x01, 0x02, 0x03]));
assert!(constant_time_eq(&[], &[]));
}
#[test]
fn constant_time_eq_unequal_same_length() {
assert!(!constant_time_eq(&[0x01, 0x02, 0x03], &[0x01, 0x02, 0x04]));
assert!(!constant_time_eq(&[0xFF], &[0x00]));
}
#[test]
fn constant_time_eq_different_lengths() {
assert!(!constant_time_eq(&[0x01, 0x02], &[0x01, 0x02, 0x03]));
assert!(!constant_time_eq(&[], &[0x00]));
}
}