Repository Public Apache-2.0
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SPB Quantum Crypto7// File : crates/spb-pqc-core/src/random/sys.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//! Raw bindings to the platform CSPRNG. Second (and last) `unsafe` island of the core.42//!43//! Each backend returns `true` only when the *entire* buffer was filled by the44//! operating system.45#![allow(unsafe_code)]4647#[cfg(target_vendor = "apple")]48mod imp {49 use core::ffi::c_void;5051 #[link(name = "Security", kind = "framework")]52 extern "C" {53 // OSStatus SecRandomCopyBytes(SecRandomRef rnd, size_t count, void *bytes);54 fn SecRandomCopyBytes(rnd: *const c_void, count: usize, bytes: *mut c_void) -> i32;55 }5657 pub fn fill(buf: &mut [u8]) -> bool {58 if buf.is_empty() {59 return true;60 }61 // SAFETY: `buf` is a valid writable region of `buf.len()` bytes;62 // a null `rnd` is `kSecRandomDefault`.63 let status =64 unsafe { SecRandomCopyBytes(core::ptr::null(), buf.len(), buf.as_mut_ptr().cast()) };65 status == 066 }67}6869#[cfg(any(target_os = "linux", target_os = "android"))]70mod imp {71 use core::ffi::{c_uint, c_void};7273 extern "C" {74 // ssize_t getrandom(void *buf, size_t buflen, unsigned int flags);75 fn getrandom(buf: *mut c_void, buflen: usize, flags: c_uint) -> isize;76 }7778 pub fn fill(buf: &mut [u8]) -> bool {79 let mut done = 0usize;80 while done < buf.len() {81 let rest = &mut buf[done..];82 // SAFETY: `rest` is a valid writable region of `rest.len()` bytes.83 let n = unsafe { getrandom(rest.as_mut_ptr().cast(), rest.len(), 0) };84 if n > 0 {85 done += n as usize;86 } else if n < 087 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted88 {89 continue;90 } else {91 return false;92 }93 }94 true95 }96}9798#[cfg(windows)]99mod imp {100 use core::ffi::c_void;101102 const BCRYPT_USE_SYSTEM_PREFERRED_RNG: u32 = 0x0000_0002;103104 #[link(name = "bcrypt")]105 extern "system" {106 // NTSTATUS BCryptGenRandom(BCRYPT_ALG_HANDLE, PUCHAR, ULONG, ULONG);107 fn BCryptGenRandom(alg: *mut c_void, buf: *mut u8, len: u32, flags: u32) -> i32;108 }109110 pub fn fill(buf: &mut [u8]) -> bool {111 for chunk in buf.chunks_mut(u32::MAX as usize) {112 // SAFETY: `chunk` is a valid writable region of `chunk.len()` bytes.113 let status = unsafe {114 BCryptGenRandom(115 core::ptr::null_mut(),116 chunk.as_mut_ptr(),117 chunk.len() as u32,118 BCRYPT_USE_SYSTEM_PREFERRED_RNG,119 )120 };121 if status != 0 {122 return false;123 }124 }125 true126 }127}128129#[cfg(target_arch = "wasm32")]130mod imp {131 use std::sync::OnceLock;132133 static BRIDGE: OnceLock<fn(&mut [u8]) -> bool> = OnceLock::new();134135 pub fn install(bridge: fn(&mut [u8]) -> bool) -> bool {136 BRIDGE.set(bridge).is_ok()137 }138139 pub fn fill(buf: &mut [u8]) -> bool {140 match BRIDGE.get() {141 Some(bridge) => bridge(buf),142 None => false, // fail closed: no host CSPRNG has been bridged143 }144 }145}146147#[cfg(not(any(148 target_vendor = "apple",149 target_os = "linux",150 target_os = "android",151 windows,152 target_arch = "wasm32"153)))]154mod imp {155 pub fn fill(_buf: &mut [u8]) -> bool {156 false // unsupported platform: fail closed157 }158}159160pub use imp::fill;161#[cfg(target_arch = "wasm32")]162pub use imp::install;163