libsoliton 0.1.3

Core cryptographic library for the LO protocol — hybrid post-quantum key exchange, signatures, ratchet, and storage encryption
Documentation
//! Cryptographically secure random byte generation.

/// Fill `buf` with cryptographically random bytes.
///
/// # Security
///
/// The caller is responsible for zeroizing `buf` when the random bytes are no
/// longer needed.
///
/// # Panics
///
/// Panics if the OS CSPRNG is unavailable. There is no safe fallback — failing
/// silently would produce predictable "random" bytes.
pub fn random_bytes(buf: &mut [u8]) {
    // getrandom internally retries EINTR. Other errors (ENOSYS, EAGAIN on
    // Linux; SecRandomCopyBytes failure on macOS) are non-recoverable.
    getrandom::fill(buf).unwrap_or_else(|e| panic!("getrandom failed: {e}"));
}

/// Generate `N` cryptographically random bytes.
///
/// # Security
///
/// The returned `[u8; N]` is `Copy` — the callee's stack copy is not zeroized
/// before return. When used for key material, callers should wrap the result
/// in `Zeroizing::new(...)` or prefer [`random_bytes`] with a caller-managed
/// `Zeroizing` buffer.
#[must_use]
pub fn random_array<const N: usize>() -> [u8; N] {
    let mut buf = [0u8; N];
    random_bytes(&mut buf);
    buf
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fills_buffer() {
        let mut buf = [0u8; 64];
        random_bytes(&mut buf);
        assert!(buf.iter().any(|&b| b != 0));
    }

    #[test]
    fn different_each_call() {
        let mut a = [0u8; 32];
        let mut b = [0u8; 32];
        random_bytes(&mut a);
        random_bytes(&mut b);
        assert_ne!(a, b);
    }

    #[test]
    fn array_correct_size() {
        // Compile-time size anchor: `random_array::<32>()` returns `[u8; 32]`.
        // Content (non-zero) is verified by `array_not_all_zeros`.
        let _arr: [u8; 32] = random_array::<32>();
    }

    #[test]
    fn array_not_all_zeros() {
        let arr = random_array::<32>();
        assert!(arr.iter().any(|&b| b != 0));
    }
}