lib-q-random 0.0.4

Unified secure random number generation for libQ post-quantum cryptography library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
// Allow clippy warnings in trait definitions
// These are legitimate patterns for API design
#![allow(clippy::struct_excessive_bools, clippy::doc_markdown)]

//! Core traits for lib-q-random
//!
//! This module defines the fundamental traits that form the interface
//! for random number generation in the libQ ecosystem.

#[cfg(feature = "alloc")]
use alloc::{
    boxed::Box,
    collections::BTreeMap,
    string::String,
};
use core::fmt;

use rand_core::{
    CryptoRng,
    Rng,
};

use crate::Result;

/// Enhanced random number generator trait for cryptographic applications
///
/// This trait extends the standard `Rng` and `CryptoRng` traits with
/// additional functionality required for secure cryptographic operations.
pub trait SecureRng: Rng + CryptoRng + Send + Sync {
    /// Fill the buffer with cryptographically secure random bytes
    ///
    /// This method provides the same functionality as `Rng::fill_bytes`
    /// but with additional security guarantees and error handling.
    ///
    /// # Arguments
    ///
    /// * `dest` - Buffer to fill with random bytes
    ///
    /// # Errors
    ///
    /// Returns an error if the random number generation fails or if
    /// the generated bytes don't meet security requirements.
    fn fill_bytes_secure(&mut self, dest: &mut [u8]) -> Result<()> {
        self.fill_bytes(dest);
        Ok(())
    }

    /// Generate a random u32 with security validation
    ///
    /// # Errors
    ///
    /// Returns an error if the random number generation fails.
    fn next_u32_secure(&mut self) -> Result<u32> {
        Ok(self.next_u32())
    }

    /// Generate a random u64 with security validation
    ///
    /// # Errors
    ///
    /// Returns an error if the random number generation fails.
    fn next_u64_secure(&mut self) -> Result<u64> {
        Ok(self.next_u64())
    }

    /// Initialize the RNG with entropy (if supported)
    ///
    /// # Arguments
    ///
    /// * `entropy` - Entropy data to initialize the RNG
    ///
    /// # Errors
    ///
    /// Returns an error if the entropy is invalid or initialization fails.
    fn initialize(&mut self, entropy: &[u8]) -> Result<()> {
        // Default implementation does nothing
        let _ = entropy;
        Ok(())
    }

    /// Check if the RNG is cryptographically secure
    ///
    /// Returns `true` if the RNG provides cryptographically secure randomness,
    /// `false` otherwise (e.g., for deterministic RNGs used in testing).
    fn is_secure(&self) -> bool {
        true
    }

    /// Get the entropy quality estimate (0.0 to 1.0)
    ///
    /// Returns an estimate of the entropy quality, where 1.0 represents
    /// perfect entropy and 0.0 represents no entropy.
    fn entropy_quality(&self) -> f64 {
        1.0
    }

    /// Get the RNG's security level
    ///
    /// Returns a description of the RNG's security characteristics.
    fn security_level(&self) -> SecurityLevel {
        if self.is_secure() {
            SecurityLevel::CryptographicallySecure
        } else {
            SecurityLevel::Deterministic
        }
    }

    /// Reseed the RNG with fresh entropy
    ///
    /// This method allows the RNG to be reseeded with fresh entropy,
    /// which is important for long-running applications.
    ///
    /// # Errors
    ///
    /// Returns an error if reseeding fails or is not supported.
    fn reseed(&mut self) -> Result<()> {
        // Default implementation does nothing
        Ok(())
    }

    /// Get the RNG's internal state size
    ///
    /// Returns the size of the RNG's internal state in bytes.
    fn state_size(&self) -> usize {
        0
    }

    /// Get the RNG's reseed interval
    ///
    /// Returns the recommended number of bytes to generate before reseeding,
    /// or `None` if reseeding is not required.
    fn reseed_interval(&self) -> Option<usize> {
        None
    }
}

/// Entropy source trait for providing random data
///
/// This trait defines the interface for entropy sources that can provide
/// random data to RNG implementations.
pub trait EntropySource: Send + Sync {
    /// Get entropy from the source
    ///
    /// # Arguments
    ///
    /// * `dest` - Buffer to fill with entropy data
    ///
    /// # Errors
    ///
    /// Returns an error if entropy cannot be obtained from the source.
    fn get_entropy(&mut self, dest: &mut [u8]) -> Result<()>;

    /// Check if the entropy source is available
    ///
    /// Returns `true` if the entropy source is available and can provide
    /// entropy, `false` otherwise.
    fn is_available(&self) -> bool {
        true
    }

    /// Get the entropy source's quality estimate (0.0 to 1.0)
    ///
    /// Returns an estimate of the entropy source's quality, where 1.0
    /// represents perfect entropy and 0.0 represents no entropy.
    fn quality(&self) -> f64 {
        1.0
    }

    /// Get the entropy source's name
    ///
    /// Returns a human-readable name for the entropy source.
    fn name(&self) -> &'static str {
        "Unknown"
    }

    /// Get the entropy source's type
    ///
    /// Returns the type of entropy source.
    fn source_type(&self) -> EntropySourceType {
        EntropySourceType::User // Default to User for custom implementations
    }

    /// Get the maximum entropy that can be obtained in one call
    ///
    /// Returns the maximum number of bytes that can be obtained in a single
    /// call to `get_entropy`, or `None` if there's no limit.
    fn max_entropy_per_call(&self) -> Option<usize> {
        None
    }

    /// Check if the entropy source requires initialization
    ///
    /// Returns `true` if the entropy source requires initialization before use.
    fn requires_initialization(&self) -> bool {
        false
    }

    /// Initialize the entropy source
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration parameters for initialization
    ///
    /// # Errors
    ///
    /// Returns an error if initialization fails.
    fn initialize(&mut self, config: &EntropyConfig) -> Result<()> {
        let _ = config;
        Ok(())
    }
}

/// RNG provider trait for creating and managing RNG instances
///
/// This trait defines the interface for RNG providers that can create
/// and manage RNG instances with different characteristics.
pub trait RngProvider: Send + Sync {
    /// Create a new RNG instance
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration for the RNG
    ///
    /// # Errors
    ///
    /// Returns an error if the RNG cannot be created.
    #[cfg(feature = "alloc")]
    fn create_rng(&self, config: &RngConfig) -> Result<Box<dyn SecureRng>>;

    /// Get the provider's name
    ///
    /// Returns a human-readable name for the provider.
    fn name(&self) -> &'static str;

    /// Get the provider's capabilities
    ///
    /// Returns the capabilities of the provider.
    fn capabilities(&self) -> ProviderCapabilities;

    /// Check if the provider supports a specific configuration
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration to check
    ///
    /// Returns `true` if the provider supports the configuration.
    fn supports_config(&self, config: &RngConfig) -> bool {
        let _ = config;
        true
    }

    /// Get the provider's priority
    ///
    /// Returns a priority value for the provider, where higher values
    /// indicate higher priority.
    fn priority(&self) -> u32 {
        0
    }
}

/// Security level enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SecurityLevel {
    /// Deterministic (not cryptographically secure)
    Deterministic,
    /// Cryptographically secure
    CryptographicallySecure,
    /// Hardware-based security
    Hardware,
    /// Software-based security
    Software,
}

impl fmt::Display for SecurityLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Deterministic => write!(f, "Deterministic"),
            Self::CryptographicallySecure => write!(f, "Cryptographically Secure"),
            Self::Hardware => write!(f, "Hardware"),
            Self::Software => write!(f, "Software"),
        }
    }
}

/// Entropy source type enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntropySourceType {
    /// Operating system entropy source
    OperatingSystem,
    /// Hardware random number generator
    Hardware,
    /// User-provided entropy
    User,
    /// Deterministic source (for testing)
    Deterministic,
}

impl fmt::Display for EntropySourceType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::OperatingSystem => write!(f, "Operating System"),
            Self::Hardware => write!(f, "Hardware"),
            Self::User => write!(f, "User"),
            Self::Deterministic => write!(f, "Deterministic"),
        }
    }
}

/// RNG configuration structure
pub struct RngConfig {
    /// Security level required
    pub security_level: SecurityLevel,
    /// Entropy source to use
    #[cfg(feature = "alloc")]
    pub entropy_source: Option<Box<dyn EntropySource>>,
    /// Reseed interval in bytes
    pub reseed_interval: Option<usize>,
    /// Additional configuration parameters
    #[cfg(feature = "alloc")]
    pub parameters: BTreeMap<String, String>,
}

impl Default for RngConfig {
    fn default() -> Self {
        Self {
            security_level: SecurityLevel::CryptographicallySecure,
            #[cfg(feature = "alloc")]
            entropy_source: None,
            reseed_interval: None,
            #[cfg(feature = "alloc")]
            parameters: BTreeMap::new(),
        }
    }
}

/// Entropy configuration structure
#[derive(Debug, Clone)]
pub struct EntropyConfig {
    /// Minimum entropy quality required
    pub min_quality: f64,
    /// Maximum entropy per call
    pub max_per_call: Option<usize>,
    /// Additional configuration parameters
    #[cfg(feature = "alloc")]
    pub parameters: BTreeMap<String, String>,
}

impl Default for EntropyConfig {
    fn default() -> Self {
        Self {
            min_quality: 0.8,
            max_per_call: None,
            #[cfg(feature = "alloc")]
            parameters: BTreeMap::new(),
        }
    }
}

/// Provider capabilities structure
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProviderCapabilities {
    /// Can provide cryptographically secure randomness
    pub secure: bool,
    /// Can provide deterministic randomness
    pub deterministic: bool,
    /// Supports hardware entropy sources
    pub hardware: bool,
    /// Supports reseeding
    pub reseeding: bool,
    /// Supports custom entropy sources
    pub custom_entropy: bool,
    /// Supports no_std environments
    pub no_std: bool,
    /// Supports WASM environments
    pub wasm: bool,
}

impl Default for ProviderCapabilities {
    fn default() -> Self {
        Self {
            secure: true,
            deterministic: false,
            hardware: false,
            reseeding: false,
            custom_entropy: false,
            no_std: true,
            wasm: false,
        }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(all(not(feature = "std"), feature = "alloc"))]
    use alloc::format;

    use super::*;

    #[test]
    fn test_security_level_ordering() {
        assert!(SecurityLevel::CryptographicallySecure > SecurityLevel::Deterministic);
        assert!(SecurityLevel::Hardware > SecurityLevel::CryptographicallySecure);
    }

    #[test]
    #[cfg(any(feature = "std", feature = "alloc"))]
    fn test_entropy_source_type_display() {
        assert_eq!(
            format!("{}", EntropySourceType::OperatingSystem),
            "Operating System"
        );
        assert_eq!(format!("{}", EntropySourceType::Hardware), "Hardware");
    }

    #[test]
    fn test_rng_config_default() {
        let config = RngConfig::default();
        assert_eq!(
            config.security_level,
            SecurityLevel::CryptographicallySecure
        );
        assert!(config.reseed_interval.is_none());
    }

    #[test]
    fn test_entropy_config_default() {
        let config = EntropyConfig::default();
        #[allow(clippy::float_cmp)]
        {
            assert_eq!(config.min_quality, 0.8);
        }
        assert!(config.max_per_call.is_none());
    }

    #[test]
    fn test_provider_capabilities_default() {
        let caps = ProviderCapabilities::default();
        assert!(caps.secure);
        assert!(!caps.deterministic);
        assert!(!caps.hardware);
        assert!(!caps.reseeding);
        assert!(!caps.custom_entropy);
        assert!(caps.no_std);
        assert!(!caps.wasm);
    }
}