AkurAI Build
Menu

Public repository / master

AkurAI-Framework / crates/crypto/src/random.rs

Latest change 3aae9f4e85241bcb775c31f5c03094becd3da56a - Pure-Rust UI layer: akurai-ui, akurai-crypto, Tailwind-grade akurai-css by Ólafur Búi Ólafsson

//! OS randomness (not available on wasm).

use std::fs::File;
use std::io::{self, Read};

use crate::hex;

/// Fill `out` with cryptographically secure bytes from `/dev/urandom`.
pub fn random_bytes(out: &mut [u8]) -> io::Result<()> {
    File::open("/dev/urandom")?.read_exact(out)
}

/// `n_bytes` of OS randomness, hex-encoded (`2 * n_bytes` characters).
pub fn random_token(n_bytes: usize) -> io::Result<String> {
    let mut buf = vec![0u8; n_bytes];
    random_bytes(&mut buf)?;
    Ok(hex(&buf))
}