Skip to main content

qualia_core_db/specialized_libs/cryptographic_library/
encryption.rs

1// Part of the cryptographic_library module (split from the former mod.rs monolith
2// per CLAUDE.md §11 — pure code motion, no behaviour change).
3use super::*;
4
5/// Encryption engine for data encryption
6pub struct EncryptionEngine {
7    encryption_algorithms: HashMap<EncryptionAlgorithm, EncryptionAlgorithmImpl>,
8    decryption_algorithms: HashMap<EncryptionAlgorithm, DecryptionAlgorithmImpl>,
9    key_derivation: KeyDerivation,
10    performance_optimizer: EncryptionPerformanceOptimizer,
11}
12
13/// Encryption algorithm implementation
14#[derive(Debug, Clone)]
15pub struct EncryptionAlgorithmImpl {
16    pub algorithm_id: String,
17    pub algorithm: EncryptionAlgorithm,
18    pub key_size: usize,
19    pub iv_size: usize,
20    pub tag_size: usize,
21    pub parameters: EncryptionParameters,
22}
23
24/// Encryption parameters
25#[derive(Debug, Clone)]
26pub struct EncryptionParameters {
27    pub mode: EncryptionMode,
28    pub padding: Option<EncryptionPadding>,
29    pub additional_data: Option<Vec<u8>>,
30    pub custom_params: HashMap<String, Vec<u8>>,
31}
32
33/// Encryption modes
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35pub enum EncryptionMode {
36    GCM,
37    CCM,
38    CTR,
39    CBC,
40    CFB,
41    OFB,
42    XTS,
43}
44
45/// Encryption padding
46#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
47pub enum EncryptionPadding {
48    PKCS7,
49    ISO10126,
50    ANSIX923,
51    ZeroPadding,
52    NoPadding,
53}
54
55/// Decryption algorithm implementation
56#[derive(Debug, Clone)]
57pub struct DecryptionAlgorithmImpl {
58    pub algorithm_id: String,
59    pub algorithm: EncryptionAlgorithm,
60    pub key_size: usize,
61    pub iv_size: usize,
62    pub tag_size: usize,
63    pub parameters: DecryptionParameters,
64}
65
66/// Decryption parameters
67#[derive(Debug, Clone)]
68pub struct DecryptionParameters {
69    pub mode: EncryptionMode,
70    pub padding: Option<EncryptionPadding>,
71    pub additional_data: Option<Vec<u8>>,
72    pub custom_params: HashMap<String, Vec<u8>>,
73}
74
75/// Key derivation
76pub struct KeyDerivation {
77    derivation_functions: HashMap<String, DerivationFunction>,
78    pub(super) derivation_parameters: DerivationParameters,
79}
80
81/// Derivation functions
82#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
83pub enum DerivationFunction {
84    HKDF,
85    PBKDF2,
86    Scrypt,
87    Argon2,
88    Custom(String),
89}
90
91/// Derivation parameters
92#[derive(Debug, Clone)]
93pub struct DerivationParameters {
94    pub salt: Vec<u8>,
95    pub iterations: u32,
96    pub memory_cost: u32,
97    pub parallelism: u32,
98    pub output_length: usize,
99}
100
101/// Encryption performance optimizer
102pub struct EncryptionPerformanceOptimizer {
103    optimization_strategies: Vec<EncryptionOptimizationStrategy>,
104    performance_metrics: EncryptionPerformanceMetrics,
105}
106
107/// Encryption optimization strategies
108#[derive(Debug, Clone, PartialEq)]
109pub enum EncryptionOptimizationStrategy {
110    BatchEncryption,
111    ParallelProcessing,
112    HardwareAcceleration,
113    MemoryOptimization,
114    Caching,
115}
116
117/// Encryption performance metrics
118#[derive(Debug, Clone)]
119pub struct EncryptionPerformanceMetrics {
120    pub average_encryption_time: f64,
121    pub average_decryption_time: f64,
122    pub throughput: f64,
123    pub memory_usage: u64,
124    pub cache_hit_rate: f64,
125}
126impl EncryptionEngine {
127    /// Creates an encryption engine with default derivation/optimizer components.
128    pub fn new() -> Self {
129        Self {
130            encryption_algorithms: HashMap::new(),
131            decryption_algorithms: HashMap::new(),
132            key_derivation: KeyDerivation::new(),
133            performance_optimizer: EncryptionPerformanceOptimizer::new(),
134        }
135    }
136
137    /// Initializes key derivation and optimizer; `CryptographicError` propagates.
138    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
139        self.key_derivation.initialize()?;
140        self.performance_optimizer.initialize()?;
141        Ok(())
142    }
143
144    /// Register an encryption algorithm implementation.
145    pub fn add_encryption_algorithm(
146        &mut self,
147        algorithm: EncryptionAlgorithm,
148        implementation: EncryptionAlgorithmImpl,
149    ) {
150        self.encryption_algorithms.insert(algorithm, implementation);
151    }
152
153    /// Look up an encryption algorithm implementation.
154    pub fn get_encryption_algorithm(
155        &self,
156        algorithm: &EncryptionAlgorithm,
157    ) -> Option<&EncryptionAlgorithmImpl> {
158        self.encryption_algorithms.get(algorithm)
159    }
160
161    /// Iterate over all registered encryption algorithm implementations.
162    pub fn list_encryption_algorithms(&self) -> impl Iterator<Item = &EncryptionAlgorithmImpl> {
163        self.encryption_algorithms.values()
164    }
165
166    /// Register a decryption algorithm implementation.
167    pub fn add_decryption_algorithm(
168        &mut self,
169        algorithm: EncryptionAlgorithm,
170        implementation: DecryptionAlgorithmImpl,
171    ) {
172        self.decryption_algorithms.insert(algorithm, implementation);
173    }
174
175    /// Look up a decryption algorithm implementation.
176    pub fn get_decryption_algorithm(
177        &self,
178        algorithm: &EncryptionAlgorithm,
179    ) -> Option<&DecryptionAlgorithmImpl> {
180        self.decryption_algorithms.get(algorithm)
181    }
182
183    /// Iterate over all registered decryption algorithm implementations.
184    pub fn list_decryption_algorithms(&self) -> impl Iterator<Item = &DecryptionAlgorithmImpl> {
185        self.decryption_algorithms.values()
186    }
187
188    /// Derive key material using HKDF-SHA256 via the embedded [`KeyDerivation`] engine.
189    pub fn derive_hkdf(&self, ikm: &[u8], info: &[u8]) -> Result<Vec<u8>, CryptographicError> {
190        self.key_derivation.derive_hkdf(ikm, info)
191    }
192
193    /// `EncryptionEngine::encrypt_data`.
194    pub fn encrypt_data(
195        &mut self,
196        key: &Key,
197        data: &[u8],
198        additional_data: Option<&[u8]>,
199    ) -> Result<EncryptedData, CryptographicError> {
200        self.encrypt_data_with(key, data, additional_data, EncryptionAlgorithm::AES256GCM)
201    }
202
203    /// Encrypt with an explicitly chosen AEAD algorithm
204    /// (AES-256-GCM, ChaCha20-Poly1305, or XChaCha20-Poly1305).
205    pub fn encrypt_data_with(
206        &mut self,
207        key: &Key,
208        data: &[u8],
209        additional_data: Option<&[u8]>,
210        algorithm: EncryptionAlgorithm,
211    ) -> Result<EncryptedData, CryptographicError> {
212        let start_time = std::time::Instant::now();
213
214        // Generate a nonce sized for the chosen algorithm
215        let iv = self.generate_iv(&algorithm)?;
216
217        // Encrypt data
218        let (ciphertext, tag) =
219            self.encrypt_with_key(&key, data, &iv, additional_data, &algorithm)?;
220
221        let mode = match algorithm {
222            EncryptionAlgorithm::AES256GCM => EncryptionMode::GCM,
223            // ChaCha20 is a counter-mode stream cipher with a Poly1305 MAC; CTR is the
224            // closest honest descriptor in the (cosmetic) EncryptionMode enum.
225            _ => EncryptionMode::CTR,
226        };
227
228        let encrypted_data = EncryptedData {
229            data_id: format!(
230                "enc_{}",
231                std::time::SystemTime::now()
232                    .duration_since(std::time::UNIX_EPOCH)
233                    .unwrap()
234                    .as_secs()
235            ),
236            algorithm: algorithm.clone(),
237            ciphertext,
238            iv,
239            tag,
240            aad: additional_data.unwrap_or(b"").to_vec(),
241            metadata: EncryptionMetadata {
242                key_id: key.key_id.clone(),
243                algorithm,
244                mode,
245                padding: Some(EncryptionPadding::NoPadding),
246                created_at: start_time.elapsed().as_millis() as u64,
247            },
248        };
249
250        // Record performance metrics
251        self.performance_optimizer
252            .record_encryption_time(start_time.elapsed().as_millis() as f64);
253
254        Ok(encrypted_data)
255    }
256
257    /// Dispatches AEAD decryption by the ciphertext's recorded algorithm, verifies the tag, and records latency metrics.
258    pub fn decrypt_data(
259        &mut self,
260        key: &Key,
261        encrypted_data: &EncryptedData,
262    ) -> Result<Vec<u8>, CryptographicError> {
263        let start_time = std::time::Instant::now();
264        // Dispatch on the algorithm the ciphertext was produced with.
265        let aad_ref = if encrypted_data.aad.is_empty() {
266            None
267        } else {
268            Some(encrypted_data.aad.as_slice())
269        };
270        let plaintext = self.decrypt_with_key(
271            &key,
272            &encrypted_data.ciphertext,
273            &encrypted_data.iv,
274            &encrypted_data.tag,
275            aad_ref,
276            &encrypted_data.algorithm,
277        )?;
278
279        // Record performance metrics
280        self.performance_optimizer
281            .record_decryption_time(start_time.elapsed().as_millis() as f64);
282
283        Ok(plaintext)
284    }
285
286    /// Expected nonce length in bytes for the given AEAD algorithm.
287    fn nonce_len(algorithm: &EncryptionAlgorithm) -> usize {
288        match algorithm {
289            EncryptionAlgorithm::XChaCha20Poly1305 => 24,
290            _ => 12, // AES-256-GCM and ChaCha20-Poly1305
291        }
292    }
293
294    fn generate_iv(&self, algorithm: &EncryptionAlgorithm) -> Result<Vec<u8>, CryptographicError> {
295        let len = Self::nonce_len(algorithm);
296        let mut iv = vec![0u8; len];
297        for b in iv.iter_mut() {
298            *b = rand::random::<u8>();
299        }
300        Ok(iv)
301    }
302
303    fn encrypt_with_key(
304        &self,
305        key: &Key,
306        data: &[u8],
307        iv: &[u8],
308        additional_data: Option<&[u8]>,
309        algorithm: &EncryptionAlgorithm,
310    ) -> Result<(Vec<u8>, Vec<u8>), CryptographicError> {
311        use aead::{AeadInOut, KeyInit};
312        if key.key_data.len() < 32 {
313            return Err(CryptographicError::EncryptionError(
314                "AEAD key must be 32 bytes".to_string(),
315            ));
316        }
317        let expected_nonce = Self::nonce_len(algorithm);
318        if iv.len() != expected_nonce {
319            return Err(CryptographicError::EncryptionError(format!(
320                "IV must be {expected_nonce} bytes for this algorithm"
321            )));
322        }
323        let aad = additional_data.unwrap_or(b"");
324        let mut buffer = data.to_vec();
325        let tag = match algorithm {
326            EncryptionAlgorithm::AES256GCM => {
327                use aes_gcm::Aes256Gcm;
328                let cipher = Aes256Gcm::new(
329                    &aes_gcm::Key::<Aes256Gcm>::try_from(&key.key_data[..32]).unwrap(),
330                );
331                cipher
332                    .encrypt_inout_detached(
333                        &aes_gcm::Nonce::try_from(iv).unwrap(),
334                        aad,
335                        (&mut buffer[..]).into(),
336                    )
337                    .map_err(|e| CryptographicError::EncryptionError(e.to_string()))?
338                    .to_vec()
339            }
340            EncryptionAlgorithm::ChaCha20Poly1305 => {
341                use chacha20poly1305::ChaCha20Poly1305;
342                let cipher = ChaCha20Poly1305::new(
343                    &chacha20poly1305::Key::try_from(&key.key_data[..32]).unwrap(),
344                );
345                cipher
346                    .encrypt_inout_detached(
347                        &chacha20poly1305::Nonce::try_from(iv).unwrap(),
348                        aad,
349                        (&mut buffer[..]).into(),
350                    )
351                    .map_err(|e| CryptographicError::EncryptionError(e.to_string()))?
352                    .to_vec()
353            }
354            EncryptionAlgorithm::XChaCha20Poly1305 => {
355                use chacha20poly1305::XChaCha20Poly1305;
356                let cipher = XChaCha20Poly1305::new(
357                    &chacha20poly1305::Key::try_from(&key.key_data[..32]).unwrap(),
358                );
359                cipher
360                    .encrypt_inout_detached(
361                        &chacha20poly1305::XNonce::try_from(iv).unwrap(),
362                        aad,
363                        (&mut buffer[..]).into(),
364                    )
365                    .map_err(|e| CryptographicError::EncryptionError(e.to_string()))?
366                    .to_vec()
367            }
368            EncryptionAlgorithm::Custom(name) => {
369                return Err(CryptographicError::UnsupportedAlgorithm(format!(
370                    "Custom cipher '{name}' not implemented"
371                )));
372            }
373        };
374        Ok((buffer, tag))
375    }
376
377    fn decrypt_with_key(
378        &self,
379        key: &Key,
380        ciphertext: &[u8],
381        iv: &[u8],
382        tag: &[u8],
383        additional_data: Option<&[u8]>,
384        algorithm: &EncryptionAlgorithm,
385    ) -> Result<Vec<u8>, CryptographicError> {
386        use aead::{AeadInOut, KeyInit};
387        if key.key_data.len() < 32 {
388            return Err(CryptographicError::DecryptionError(
389                "AEAD key must be 32 bytes".to_string(),
390            ));
391        }
392        let expected_nonce = Self::nonce_len(algorithm);
393        if iv.len() != expected_nonce {
394            return Err(CryptographicError::DecryptionError(format!(
395                "IV must be {expected_nonce} bytes for this algorithm"
396            )));
397        }
398        if tag.len() != 16 {
399            return Err(CryptographicError::DecryptionError(
400                "AEAD tag must be 16 bytes".to_string(),
401            ));
402        }
403        let aad = additional_data.unwrap_or(b"");
404        let mut buffer = ciphertext.to_vec();
405        match algorithm {
406            EncryptionAlgorithm::AES256GCM => {
407                use aes_gcm::Aes256Gcm;
408                let cipher = Aes256Gcm::new(
409                    &aes_gcm::Key::<Aes256Gcm>::try_from(&key.key_data[..32]).unwrap(),
410                );
411                cipher
412                    .decrypt_inout_detached(
413                        &aes_gcm::Nonce::try_from(iv).unwrap(),
414                        aad,
415                        (&mut buffer[..]).into(),
416                        &aes_gcm::Tag::try_from(tag).unwrap(),
417                    )
418                    .map_err(|e| CryptographicError::DecryptionError(e.to_string()))?;
419            }
420            EncryptionAlgorithm::ChaCha20Poly1305 => {
421                use chacha20poly1305::ChaCha20Poly1305;
422                let cipher = ChaCha20Poly1305::new(
423                    &chacha20poly1305::Key::try_from(&key.key_data[..32]).unwrap(),
424                );
425                cipher
426                    .decrypt_inout_detached(
427                        &chacha20poly1305::Nonce::try_from(iv).unwrap(),
428                        aad,
429                        (&mut buffer[..]).into(),
430                        &chacha20poly1305::Tag::try_from(tag).unwrap(),
431                    )
432                    .map_err(|e| CryptographicError::DecryptionError(e.to_string()))?;
433            }
434            EncryptionAlgorithm::XChaCha20Poly1305 => {
435                use chacha20poly1305::XChaCha20Poly1305;
436                let cipher = XChaCha20Poly1305::new(
437                    &chacha20poly1305::Key::try_from(&key.key_data[..32]).unwrap(),
438                );
439                cipher
440                    .decrypt_inout_detached(
441                        &chacha20poly1305::XNonce::try_from(iv).unwrap(),
442                        aad,
443                        (&mut buffer[..]).into(),
444                        &chacha20poly1305::Tag::try_from(tag).unwrap(),
445                    )
446                    .map_err(|e| CryptographicError::DecryptionError(e.to_string()))?;
447            }
448            EncryptionAlgorithm::Custom(name) => {
449                return Err(CryptographicError::UnsupportedAlgorithm(format!(
450                    "Custom cipher '{name}' not implemented"
451                )));
452            }
453        }
454        Ok(buffer)
455    }
456}
457
458impl KeyDerivation {
459    /// Creates a key-derivation component.
460    pub fn new() -> Self {
461        Self {
462            derivation_functions: HashMap::new(),
463            derivation_parameters: DerivationParameters {
464                salt: vec![0u8; 16],
465                iterations: 100000,
466                memory_cost: 65536,
467                parallelism: 4,
468                output_length: 32,
469            },
470        }
471    }
472
473    /// No-op returning `Ok(())`.
474    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
475        Ok(())
476    }
477
478    /// Register a derivation function under a named key.
479    pub fn add_derivation_function(&mut self, name: String, function: DerivationFunction) {
480        self.derivation_functions.insert(name, function);
481    }
482
483    /// Look up a derivation function by name.
484    pub fn get_derivation_function(&self, name: &str) -> Option<&DerivationFunction> {
485        self.derivation_functions.get(name)
486    }
487
488    /// Iterate over all registered derivation function names.
489    pub fn list_derivation_functions(
490        &self,
491    ) -> impl Iterator<Item = (&String, &DerivationFunction)> {
492        self.derivation_functions.iter()
493    }
494
495    /// Derive `output_length` bytes from input keying material using HKDF-SHA256.
496    ///
497    /// Uses the configured `derivation_parameters.salt` and `output_length`. `info`
498    /// is the application-specific context/label that domain-separates derived keys.
499    pub fn derive_hkdf(&self, ikm: &[u8], info: &[u8]) -> Result<Vec<u8>, CryptographicError> {
500        use hkdf::Hkdf;
501        use sha2::Sha256;
502        let hk = Hkdf::<Sha256>::new(Some(&self.derivation_parameters.salt), ikm);
503        let mut okm = vec![0u8; self.derivation_parameters.output_length];
504        hk.expand(info, &mut okm)
505            .map_err(|e| CryptographicError::EncryptionError(format!("HKDF expand failed: {e}")))?;
506        Ok(okm)
507    }
508}
509
510impl EncryptionPerformanceOptimizer {
511    /// Creates an encryption performance optimizer.
512    pub fn new() -> Self {
513        Self {
514            optimization_strategies: vec![
515                EncryptionOptimizationStrategy::BatchEncryption,
516                EncryptionOptimizationStrategy::ParallelProcessing,
517            ],
518            performance_metrics: EncryptionPerformanceMetrics {
519                average_encryption_time: 0.0,
520                average_decryption_time: 0.0,
521                throughput: 0.0,
522                memory_usage: 0,
523                cache_hit_rate: 0.0,
524            },
525        }
526    }
527
528    /// No-op returning `Ok(())`.
529    pub fn initialize(&mut self) -> Result<(), CryptographicError> {
530        Ok(())
531    }
532
533    /// Get the configured optimization strategies.
534    pub fn optimization_strategies(&self) -> &[EncryptionOptimizationStrategy] {
535        &self.optimization_strategies
536    }
537
538    /// Add an optimization strategy if not already present.
539    pub fn add_optimization_strategy(&mut self, strategy: EncryptionOptimizationStrategy) {
540        if !self.optimization_strategies.contains(&strategy) {
541            self.optimization_strategies.push(strategy);
542        }
543    }
544
545    /// Record an encryption operation duration (milliseconds).
546    pub fn record_encryption_time(&mut self, duration_ms: f64) {
547        let m = &mut self.performance_metrics;
548        if m.average_encryption_time == 0.0 {
549            m.average_encryption_time = duration_ms;
550        } else {
551            m.average_encryption_time = 0.9 * m.average_encryption_time + 0.1 * duration_ms;
552        }
553        if m.average_encryption_time > 0.0 {
554            m.throughput = 1000.0 / m.average_encryption_time;
555        }
556    }
557
558    /// Record a decryption operation duration (milliseconds).
559    pub fn record_decryption_time(&mut self, duration_ms: f64) {
560        let m = &mut self.performance_metrics;
561        if m.average_decryption_time == 0.0 {
562            m.average_decryption_time = duration_ms;
563        } else {
564            m.average_decryption_time = 0.9 * m.average_decryption_time + 0.1 * duration_ms;
565        }
566    }
567
568    /// Get a snapshot of the current performance metrics.
569    pub fn metrics(&self) -> &EncryptionPerformanceMetrics {
570        &self.performance_metrics
571    }
572}
573
574impl EncryptionPerformanceMetrics {
575    /// Creates zeroed encryption metrics.
576    pub fn new() -> Self {
577        Self {
578            average_encryption_time: 0.0,
579            average_decryption_time: 0.0,
580            throughput: 0.0,
581            memory_usage: 0,
582            cache_hit_rate: 0.0,
583        }
584    }
585}