hopr_crypto_random/
lib.rs

1//! This Rust crate contains implementation of common random number generation functions.
2//! All functions and types from this crate supply cryptographically secure random numbers.
3//!
4//! Instead of relying on external crates, all HOPR crates in this monorepo should
5//! exclusively rely on randomness functions only from this crate.
6//! Besides that, the `OsRng` type exported from this crate can be used if a type implementing
7//! random traits is necessary.
8
9use generic_array::{ArrayLength, GenericArray};
10use rand::CryptoRng;
11
12pub use rand::{Rng, RngCore};
13
14/// Maximum random integer that can be generated.
15/// This is the last positive 64-bit value in the two's complement representation.
16pub const MAX_RANDOM_INTEGER: u64 = 9007199254740991;
17
18/// Gets the default cryptographically secure random number generator.
19///
20/// **WARNING** On debug builds with the ` fixed_rng ` feature enabled during
21/// compilation, this function will return an RNG with a fixed seed, which is *NOT SECURE*!
22/// This is reserved for deterministic testing.
23#[cfg(all(debug_assertions, feature = "fixed_rng"))]
24#[inline]
25pub fn rng() -> impl RngCore + CryptoRng {
26    use rand::SeedableRng;
27    rand::rngs::StdRng::from_seed([
28        0x5f, 0x57, 0xce, 0x2a, 0x84, 0x14, 0x7e, 0x88, 0x43, 0x56, 0x44, 0x56, 0x7f, 0x90, 0x4f, 0xb2, 0x04, 0x6b,
29        0x18, 0x42, 0x75, 0x69, 0xbe, 0x53, 0xb2, 0x29, 0x78, 0xbd, 0xf3, 0x0a, 0xda, 0xba,
30    ])
31}
32
33/// Gets the default cryptographically secure random number generator.
34#[cfg(any(not(debug_assertions), not(feature = "fixed_rng")))]
35#[inline]
36pub fn rng() -> impl RngCore + CryptoRng {
37    rand::rngs::OsRng
38}
39
40/// Returns `true` if the build is using an **insecure** RNG with a fixed seed.
41///
42/// See also [`rng`].
43#[inline]
44pub const fn is_rng_fixed() -> bool {
45    cfg!(debug_assertions) && cfg!(feature = "fixed_rng")
46}
47
48/// Generates a random float uniformly distributed between 0 (inclusive) and 1 (exclusive).
49#[inline]
50pub fn random_float() -> f64 {
51    rng().gen()
52}
53
54/// Generates a random float uniformly distributed in the given range.
55#[inline]
56pub fn random_float_in_range(range: std::ops::Range<f64>) -> f64 {
57    rng().gen_range(range)
58}
59
60/// Generates a random unsigned integer which is at least `start` and optionally strictly less than `end`.
61/// If `end` is not given, the ` MAX_RANDOM_INTEGER ` value is used.
62/// The caller must make sure that 0 <= `start` < `end` <= `MAX_RANDOM_INTEGER`, otherwise the function will panic.
63pub fn random_integer(start: u64, end: Option<u64>) -> u64 {
64    let real_end = end.unwrap_or(MAX_RANDOM_INTEGER);
65
66    assert!(
67        real_end > start && real_end <= MAX_RANDOM_INTEGER,
68        "bounds must be 0 < {start} < {real_end} <= {MAX_RANDOM_INTEGER}"
69    );
70
71    let bound = real_end - start;
72    start + rng().gen_range(0..bound)
73}
74
75/// Fills the specific number of bytes starting from the given offset in the given buffer.
76#[inline]
77pub fn random_fill(buffer: &mut [u8]) {
78    rng().fill_bytes(buffer);
79}
80
81/// Allocates an array of the given size and fills it with random bytes
82pub fn random_bytes<const T: usize>() -> [u8; T] {
83    let mut ret = [0u8; T];
84    random_fill(&mut ret);
85    ret
86}
87
88/// Allocates `GenericArray` of the given size and fills it with random bytes
89pub fn random_array<L: ArrayLength<u8>>() -> GenericArray<u8, L> {
90    let mut ret = GenericArray::default();
91    random_fill(&mut ret);
92    ret
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn test_random_integer() {
101        assert!(random_integer(10, None) > 10);
102
103        let bounded = random_integer(10, Some(20));
104        assert!((10..20).contains(&bounded));
105    }
106
107    #[test]
108    fn test_random_float() {
109        let f = random_float();
110        assert!((0.0..1.0).contains(&f));
111    }
112
113    #[test]
114    fn test_random_fill() {
115        let mut buffer = [0u8; 10];
116        // 7 bytes with indices 2,3,4,5,6,7,8 will be filled with random bytes, the other stay zero
117        random_fill(&mut buffer[2..9]);
118        assert_eq!(0, buffer[0]);
119        assert_eq!(0, buffer[1]);
120        assert_eq!(0, buffer[9]);
121    }
122}