trelent-hyok 0.1.12

A Rust library implementing Hold Your Own Key (HYOK) encryption patterns with support for multiple cloud providers
Documentation
//! Fixed-length cryptographic key generation.
//!
//! This module provides secure generation of fixed-length Data Encryption Keys (DEKs)
//! using the operating system's cryptographically secure random number generator.
//! It ensures:
//!
//! - Cryptographic security
//! - Consistent key lengths
//! - System-level entropy
//! - Thread safety

use rand::rngs::OsRng;
use rand::RngCore;

use crate::dek::generator::DEKKeyGenerator;
use crate::error::generator::GenerateKeyError;

/// A key generator that produces cryptographically secure random keys
/// of a fixed length using the operating system's random number generator.
///
/// This generator:
/// - Uses the system's secure RNG
/// - Produces keys of consistent length
/// - Ensures cryptographic quality
/// - Provides thread-safe operation
///
/// # Security
///
/// This implementation:
/// - Uses OS-provided entropy
/// - Generates cryptographically secure random bytes
/// - Maintains key length consistency
///
/// # Example
/// ```no_run
/// use hyokashi::FixedLengthGenerator;
///
/// // Create a generator for 32-byte keys
/// let generator = FixedLengthGenerator::new(32);
/// let key = generator.generate_key()?;
/// assert_eq!(key.len(), 32);
/// ```
#[derive(Debug)]
pub struct FixedLengthGenerator(pub(crate) usize);

impl FixedLengthGenerator {
    /// Creates a new `FixedLengthGenerator` that will generate keys of the specified length.
    ///
    /// # Arguments
    ///
    /// * `len` - The desired number of bytes in the generated key
    pub fn new(len: usize) -> FixedLengthGenerator {
        FixedLengthGenerator(len)
    }
}

impl DEKKeyGenerator for FixedLengthGenerator {
    /// Generates a new random key of the configured length using the OS random number generator.
    ///
    /// # Returns
    ///
    /// A vector of random bytes with length matching the configured size.
    fn generate_key(&self) -> Result<Vec<u8>, GenerateKeyError> {
        let mut key: Vec<u8> = vec![0; self.0];
        OsRng.fill_bytes(&mut key);
        Ok(key.to_vec())
    }
}