Skip to main content

crypto_csprng/
rng.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5use crypto_core::{CryptoError, RngFailureKind, RngOutputKind};
6use getrandom::{rand_core::TryRng, SysRng};
7
8/// A source of cryptographically secure random bytes.
9pub trait SecureRandom {
10    /// Fills `output` with secure random bytes, tagging any error with `kind`.
11    /// Returns an error if entropy is unavailable.
12    fn fill_secure(&mut self, output: &mut [u8], kind: RngOutputKind) -> Result<(), CryptoError>;
13}
14
15/// [`SecureRandom`] implementation backed by the operating system's CSPRNG.
16#[derive(Default)]
17pub struct OsSecureRandom;
18
19impl SecureRandom for OsSecureRandom {
20    fn fill_secure(&mut self, output: &mut [u8], kind: RngOutputKind) -> Result<(), CryptoError> {
21        SysRng.try_fill_bytes(output).map_err(|_| CryptoError::Rng {
22            output: kind,
23            kind: RngFailureKind::EntropyUnavailable,
24        })
25    }
26}