trelent-hyok 0.1.12

A Rust library implementing Hold Your Own Key (HYOK) encryption patterns with support for multiple cloud providers
Documentation
//! Custom key generation implementation.
//!
//! This module enables custom Data Encryption Key (DEK) generation by allowing
//! users to provide their own generation functions. It supports:
//!
//! - Custom key generation algorithms
//! - Flexible key formats
//! - Error handling
//! - Thread-safe implementation

use crate::dek::generator::DEKKeyGenerator;
use crate::error::generator::GenerateKeyError;
use std::sync::Arc;

/// A customizable Data Encryption Key generator using a user-defined closure.
///
/// This generator allows integration with any key generation algorithm by accepting
/// a closure that produces keys. Features include:
///
/// - Flexible key generation logic
/// - Thread-safe implementation
/// - Error handling
/// - Custom key formats
///
/// # Security
///
/// When implementing custom generation logic, ensure:
/// - Sufficient entropy for key material
/// - Appropriate key lengths
/// - Secure random number generation
/// - Protection of sensitive data
///
/// # Example
/// ```no_run
/// use hyokashi::{CustomGenerator, GenerateKeyError};
///
/// // Define custom key generation logic
/// let custom_gen = || {
///     // Implement secure key generation...
///     Ok(vec![1, 2, 3, 4])
/// };
///
/// let generator = CustomGenerator::new(custom_gen);
/// let key = generator.generate_key()?;
/// ```
pub struct CustomGenerator {
    generate_fn: Arc<dyn (Fn() -> Result<Vec<u8>, GenerateKeyError>) + Send + Sync>,
}

impl CustomGenerator {
    /// Creates a new `CustomGenerator` with the provided key generation function.
    ///
    /// # Arguments
    ///
    /// * `generate_fn` - A closure that generates encryption keys.
    ///
    /// # Returns
    ///
    /// A new `CustomGenerator` that will use the provided function to generate keys.
    pub fn new<G>(generate_fn: G) -> Self
        where G: Fn() -> Result<Vec<u8>, GenerateKeyError> + Send + Sync + 'static
    {
        CustomGenerator {
            generate_fn: Arc::new(generate_fn),
        }
    }
}

impl DEKKeyGenerator for CustomGenerator {
    /// Generates a new key by calling the user-provided generation function.
    ///
    /// # Errors
    ///
    /// Returns a `GenerateKeyError` if the key generation function fails.
    fn generate_key(&self) -> Result<Vec<u8>, GenerateKeyError> {
        (self.generate_fn)()
    }
}