SPB Git

Repository Public Apache-2.0

mod.rs 4.7 KB 138 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SPB Quantum Crypto7// File             : crates/spb-pqc-core/src/random/mod.rs8// Module           : Crates9// Repository       : https://git.spboucher.ai/spb-quantum-crypto10// Project Website  : https://pqce.spboucher.ai11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : Apache-2.033//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041//! Operating-system CSPRNG access. Fail-closed, no fallback generator.42//!43//! | Platform                 | Source                                            |44//! |--------------------------|---------------------------------------------------|45//! | macOS, iOS, tvOS, …      | `SecRandomCopyBytes(kSecRandomDefault, …)`        |46//! | Linux, Android           | `getrandom(2)` with `flags = 0` (blocks until seeded) |47//! | Windows                  | `BCryptGenRandom(BCRYPT_USE_SYSTEM_PREFERRED_RNG)`|48//! | wasm32                   | host bridge installed by `spb-pqc-wasm` (`crypto.getRandomValues`) |49//! | anything else            | always `Error::RandomFailure`                     |50//!51//! There is deliberately no user-supplied generator, no seeding API and no52//! deterministic mode outside the `kat` test feature.5354mod sys;5556use crate::error::{Error, Result};5758/// Largest single request accepted (public limit, keeps host bridges simple).59pub const MAX_REQUEST: usize = 1 << 20;6061/// Fills `buf` with bytes from the operating-system CSPRNG.62///63/// On failure the buffer content is unspecified and **must not be used**; every64/// caller in this crate propagates the error and aborts the operation.65pub fn fill(buf: &mut [u8]) -> Result<()> {66    if buf.len() > MAX_REQUEST {67        return Err(Error::SizeLimitExceeded);68    }69    #[cfg(any(test, feature = "kat"))]70    if testing::failure_forced() {71        return Err(Error::RandomFailure);72    }73    if sys::fill(buf) {74        Ok(())75    } else {76        Err(Error::RandomFailure)77    }78}7980/// Installs the entropy bridge on `wasm32` targets. The first installation wins.81///82/// The bridge must fill the whole slice from `crypto.getRandomValues` (or the83/// Node.js equivalent) and return `true`, or return `false` on any failure.84#[cfg(target_arch = "wasm32")]85pub fn install_host_bridge(bridge: fn(&mut [u8]) -> bool) -> bool {86    sys::install(bridge)87}8889/// Test-only fault injection: makes [`fill`] fail on the current thread.90#[cfg(any(test, feature = "kat"))]91pub mod testing {92    use std::cell::Cell;9394    thread_local! {95        static FORCE_FAILURE: Cell<bool> = const { Cell::new(false) };96    }9798    /// Forces (or stops forcing) RNG failure on the calling thread.99    pub fn force_failure(on: bool) {100        FORCE_FAILURE.with(|f| f.set(on));101    }102103    pub(super) fn failure_forced() -> bool {104        FORCE_FAILURE.with(|f| f.get())105    }106}107108#[cfg(test)]109mod tests {110    use super::*;111112    #[test]113    fn fills_and_differs() {114        let mut a = [0u8; 64];115        let mut b = [0u8; 64];116        fill(&mut a).unwrap();117        fill(&mut b).unwrap();118        assert_ne!(a, b, "two 512-bit draws must differ");119        assert_ne!(a, [0u8; 64]);120    }121122    #[test]123    fn empty_and_limit() {124        fill(&mut []).unwrap();125        let mut big = vec![0u8; MAX_REQUEST + 1];126        assert_eq!(fill(&mut big), Err(Error::SizeLimitExceeded));127    }128129    #[test]130    fn forced_failure_is_reported() {131        testing::force_failure(true);132        let mut a = [0u8; 8];133        assert_eq!(fill(&mut a), Err(Error::RandomFailure));134        testing::force_failure(false);135        fill(&mut a).unwrap();136    }137}138
Files main
Menu

Theme