ring_native_ossl/rand.rs
1//! Cryptographically secure random byte generation, mirroring `ring::rand`.
2//!
3//! [`SystemRandom`] delegates to OpenSSL's `RAND_bytes` and implements the
4//! [`SecureRandom`] trait, which serves the same role as `ring::rand::SecureRandom`
5//! as a bound in [`crate::agreement`] and [`crate::signature`].
6
7use crate::error::Unspecified;
8use native_ossl::rand::Rand;
9
10/// A random number generator backed by OpenSSL (`RAND_bytes`).
11///
12/// Mirrors `ring::rand::SystemRandom`.
13#[derive(Debug, Clone)]
14pub struct SystemRandom;
15
16impl SystemRandom {
17 #[must_use]
18 pub fn new() -> Self {
19 Self
20 }
21}
22
23impl Default for SystemRandom {
24 fn default() -> Self {
25 Self::new()
26 }
27}
28
29/// Sealed trait, mirroring `ring::rand::SecureRandom`.
30pub trait SecureRandom: sealed::SecureRandom {
31 /// # Errors
32 ///
33 /// Returns `Unspecified` if the random number generator fails.
34 fn fill(&self, dest: &mut [u8]) -> Result<(), Unspecified>;
35}
36
37mod sealed {
38 pub trait SecureRandom {}
39}
40
41impl sealed::SecureRandom for SystemRandom {}
42
43impl SecureRandom for SystemRandom {
44 fn fill(&self, dest: &mut [u8]) -> Result<(), Unspecified> {
45 Rand::fill(dest).map_err(|_| Unspecified)
46 }
47}