voided_core/util/
mod.rs

1//! Utility functions and helpers.
2
3use alloc::vec::Vec;
4use rand::RngCore;
5use zeroize::Zeroize;
6
7/// Generate random bytes
8pub fn random_bytes(length: usize) -> Vec<u8> {
9    let mut bytes = vec![0u8; length];
10    rand::thread_rng().fill_bytes(&mut bytes);
11    bytes
12}
13
14/// Securely wipe a buffer by overwriting with zeros
15pub fn secure_wipe(buffer: &mut [u8]) {
16    buffer.zeroize();
17}
18
19/// Constant-time comparison of two byte slices
20pub fn constant_time_compare(a: &[u8], b: &[u8]) -> bool {
21    constant_time_eq::constant_time_eq(a, b)
22}
23
24#[cfg(test)]
25mod tests {
26    use super::*;
27
28    #[test]
29    fn test_random_bytes() {
30        let bytes1 = random_bytes(32);
31        let bytes2 = random_bytes(32);
32        
33        assert_eq!(bytes1.len(), 32);
34        assert_eq!(bytes2.len(), 32);
35        assert_ne!(bytes1, bytes2); // Extremely unlikely to be equal
36    }
37
38    #[test]
39    fn test_secure_wipe() {
40        let mut buffer = vec![0xAA; 32];
41        secure_wipe(&mut buffer);
42        assert!(buffer.iter().all(|&b| b == 0));
43    }
44
45    #[test]
46    fn test_constant_time_compare() {
47        let a = [1, 2, 3, 4];
48        let b = [1, 2, 3, 4];
49        let c = [1, 2, 3, 5];
50        
51        assert!(constant_time_compare(&a, &b));
52        assert!(!constant_time_compare(&a, &c));
53    }
54}
55