Skip to main content

oxirs_stream/security/
post_quantum.rs

1//! # Post-Quantum Cryptography Engine
2//!
3//! Advanced post-quantum cryptographic operations including key generation,
4//! signing, verification, and key encapsulation (KEM) for OxiRS Stream.
5//!
6//! Enable the `post-quantum` feature flag to activate real pqcrypto implementations.
7
8use anyhow::{anyhow, Result};
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use std::sync::Arc;
13use std::time::Instant;
14use tokio::sync::RwLock;
15#[cfg(feature = "post-quantum")]
16use uuid::Uuid;
17
18use super::{EncryptionAlgorithm, PostQuantumConfig, PostQuantumSignature};
19
20/// Post-quantum cryptographic engine for advanced security operations
21pub struct PostQuantumCryptoEngine {
22    config: Arc<PostQuantumConfig>,
23    key_store: Arc<RwLock<HashMap<String, PostQuantumKeyPair>>>,
24    signature_cache: Arc<RwLock<HashMap<String, SignatureInfo>>>,
25    metrics: Arc<RwLock<PQCryptoMetrics>>,
26}
27
28impl PostQuantumCryptoEngine {
29    /// Create a new post-quantum crypto engine
30    pub fn new(config: PostQuantumConfig) -> Self {
31        Self {
32            config: Arc::new(config),
33            key_store: Arc::new(RwLock::new(HashMap::new())),
34            signature_cache: Arc::new(RwLock::new(HashMap::new())),
35            metrics: Arc::new(RwLock::new(PQCryptoMetrics::default())),
36        }
37    }
38
39    /// Generate a new post-quantum key pair
40    pub async fn generate_keypair(
41        &self,
42        algorithm: &PostQuantumSignature,
43    ) -> Result<PostQuantumKeyPair> {
44        let start_time = Instant::now();
45
46        let keypair = match algorithm {
47            PostQuantumSignature::Dilithium2
48            | PostQuantumSignature::Dilithium3
49            | PostQuantumSignature::Dilithium5 => {
50                self.generate_dilithium_keypair(algorithm).await?
51            }
52            PostQuantumSignature::SphincsPlusSha2128s
53            | PostQuantumSignature::SphincsPlusSha2256s => {
54                self.generate_sphincs_keypair(algorithm).await?
55            }
56            PostQuantumSignature::Falcon512 | PostQuantumSignature::Falcon1024 => {
57                self.generate_falcon_keypair(algorithm).await?
58            }
59            _ => {
60                return Err(anyhow!(
61                    "Post-quantum algorithm {:?} is not yet implemented. \
62                     Supported algorithms: Dilithium2/3/5, SPHINCS+-SHA2-128s/256s, Falcon512/1024",
63                    algorithm
64                ));
65            }
66        };
67
68        // Update metrics
69        {
70            let mut metrics = self.metrics.write().await;
71            metrics.key_generation_count += 1;
72            metrics.avg_key_generation_time_ms = (metrics.avg_key_generation_time_ms
73                + start_time.elapsed().as_millis() as f64)
74                / 2.0;
75        }
76
77        // Store the key pair
78        {
79            let mut store = self.key_store.write().await;
80            store.insert(keypair.id.clone(), keypair.clone());
81        }
82
83        Ok(keypair)
84    }
85
86    /// Sign data using post-quantum signature.
87    ///
88    /// Returns the raw signature bytes. Enable the `post-quantum` feature flag
89    /// for a real cryptographic implementation backed by pqcrypto.
90    pub async fn sign(&self, key_id: &str, data: &[u8]) -> Result<Vec<u8>> {
91        let start_time = Instant::now();
92
93        let key_store = self.key_store.read().await;
94        let keypair = key_store
95            .get(key_id)
96            .ok_or_else(|| anyhow!("Key not found: {}", key_id))?;
97
98        let signature_bytes = match keypair.algorithm {
99            PostQuantumSignature::Dilithium2
100            | PostQuantumSignature::Dilithium3
101            | PostQuantumSignature::Dilithium5 => {
102                self.dilithium_sign(&keypair.private_key, data, &keypair.algorithm)
103                    .await?
104            }
105            PostQuantumSignature::SphincsPlusSha2128s
106            | PostQuantumSignature::SphincsPlusSha2128f
107            | PostQuantumSignature::SphincsPlusSha2192s
108            | PostQuantumSignature::SphincsPlusSha2192f
109            | PostQuantumSignature::SphincsPlusSha2256s
110            | PostQuantumSignature::SphincsPlusSha2256f
111            | PostQuantumSignature::SphincsPlusShake128s
112            | PostQuantumSignature::SphincsPlusShake128f
113            | PostQuantumSignature::SphincsPlusShake192s
114            | PostQuantumSignature::SphincsPlusShake192f
115            | PostQuantumSignature::SphincsPlusShake256s
116            | PostQuantumSignature::SphincsPlusShake256f => {
117                self.sphincs_sign(&keypair.private_key, data, &keypair.algorithm)
118                    .await?
119            }
120            PostQuantumSignature::Falcon512 | PostQuantumSignature::Falcon1024 => {
121                self.falcon_sign(&keypair.private_key, data, &keypair.algorithm)
122                    .await?
123            }
124            _ => {
125                return Err(anyhow!(
126                    "Signing with {:?} not implemented",
127                    keypair.algorithm
128                ));
129            }
130        };
131
132        // Update metrics
133        {
134            let mut metrics = self.metrics.write().await;
135            metrics.signature_count += 1;
136            metrics.avg_signing_time_ms =
137                (metrics.avg_signing_time_ms + start_time.elapsed().as_millis() as f64) / 2.0;
138        }
139
140        Ok(signature_bytes)
141    }
142
143    /// Verify post-quantum signature.
144    ///
145    /// Enable the `post-quantum` feature flag for a real cryptographic implementation.
146    pub async fn verify(
147        &self,
148        public_key: &[u8],
149        data: &[u8],
150        signature: &[u8],
151        algorithm: &PostQuantumSignature,
152    ) -> Result<bool> {
153        let start_time = Instant::now();
154
155        let is_valid = match algorithm {
156            PostQuantumSignature::Dilithium2
157            | PostQuantumSignature::Dilithium3
158            | PostQuantumSignature::Dilithium5 => {
159                self.dilithium_verify(public_key, data, signature, algorithm)
160                    .await?
161            }
162            PostQuantumSignature::SphincsPlusSha2128s
163            | PostQuantumSignature::SphincsPlusSha2128f
164            | PostQuantumSignature::SphincsPlusSha2192s
165            | PostQuantumSignature::SphincsPlusSha2192f
166            | PostQuantumSignature::SphincsPlusSha2256s
167            | PostQuantumSignature::SphincsPlusSha2256f
168            | PostQuantumSignature::SphincsPlusShake128s
169            | PostQuantumSignature::SphincsPlusShake128f
170            | PostQuantumSignature::SphincsPlusShake192s
171            | PostQuantumSignature::SphincsPlusShake192f
172            | PostQuantumSignature::SphincsPlusShake256s
173            | PostQuantumSignature::SphincsPlusShake256f => {
174                self.sphincs_verify(public_key, data, signature, algorithm)
175                    .await?
176            }
177            PostQuantumSignature::Falcon512 | PostQuantumSignature::Falcon1024 => {
178                self.falcon_verify(public_key, data, signature, algorithm)
179                    .await?
180            }
181            _ => {
182                return Err(anyhow!("Verification for {:?} not implemented", algorithm));
183            }
184        };
185
186        // Update metrics
187        {
188            let mut metrics = self.metrics.write().await;
189            metrics.verification_count += 1;
190            metrics.avg_verification_time_ms =
191                (metrics.avg_verification_time_ms + start_time.elapsed().as_millis() as f64) / 2.0;
192            if is_valid {
193                metrics.successful_verifications += 1;
194            }
195        }
196
197        Ok(is_valid)
198    }
199
200    /// Perform key encapsulation using post-quantum KEM
201    pub async fn encapsulate(
202        &self,
203        public_key: &[u8],
204        algorithm: &EncryptionAlgorithm,
205    ) -> Result<(Vec<u8>, Vec<u8>)> {
206        match algorithm {
207            EncryptionAlgorithm::Kyber768 => self.kyber_encapsulate(public_key).await,
208            EncryptionAlgorithm::NewHope1024 => self.newhope_encapsulate(public_key).await,
209            EncryptionAlgorithm::FrodoKEM976 => self.frodokem_encapsulate(public_key).await,
210            _ => Err(anyhow!("KEM algorithm {:?} not implemented", algorithm)),
211        }
212    }
213
214    /// Perform key decapsulation using post-quantum KEM
215    pub async fn decapsulate(
216        &self,
217        private_key: &[u8],
218        ciphertext: &[u8],
219        algorithm: &EncryptionAlgorithm,
220    ) -> Result<Vec<u8>> {
221        match algorithm {
222            EncryptionAlgorithm::Kyber768 => self.kyber_decapsulate(private_key, ciphertext).await,
223            EncryptionAlgorithm::NewHope1024 => {
224                self.newhope_decapsulate(private_key, ciphertext).await
225            }
226            EncryptionAlgorithm::FrodoKEM976 => {
227                self.frodokem_decapsulate(private_key, ciphertext).await
228            }
229            _ => Err(anyhow!("KEM algorithm {:?} not implemented", algorithm)),
230        }
231    }
232
233    // -----------------------------------------------------------------------
234    // Private implementation methods — feature-gated on "post-quantum"
235    // -----------------------------------------------------------------------
236
237    /// Generate a Dilithium key pair.
238    ///
239    /// With `--features post-quantum` this calls the real pqcrypto-dilithium
240    /// C implementation.  Without the feature the method returns an error
241    /// telling the caller which flag to enable.
242    #[cfg(feature = "post-quantum")]
243    async fn generate_dilithium_keypair(
244        &self,
245        variant: &PostQuantumSignature,
246    ) -> Result<PostQuantumKeyPair> {
247        use pqcrypto_traits::sign::{PublicKey as _, SecretKey as _};
248        let (pk_bytes, sk_bytes) = match variant {
249            PostQuantumSignature::Dilithium2 => {
250                let (pk, sk) = pqcrypto_dilithium::dilithium2::keypair();
251                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
252            }
253            PostQuantumSignature::Dilithium3 => {
254                let (pk, sk) = pqcrypto_dilithium::dilithium3::keypair();
255                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
256            }
257            PostQuantumSignature::Dilithium5 => {
258                let (pk, sk) = pqcrypto_dilithium::dilithium5::keypair();
259                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
260            }
261            other => {
262                return Err(anyhow!(
263                    "generate_dilithium_keypair: unexpected variant {:?}",
264                    other
265                ))
266            }
267        };
268        Ok(PostQuantumKeyPair {
269            id: Uuid::new_v4().to_string(),
270            algorithm: variant.clone(),
271            public_key: pk_bytes,
272            private_key: sk_bytes,
273            created_at: Utc::now(),
274        })
275    }
276
277    #[cfg(not(feature = "post-quantum"))]
278    async fn generate_dilithium_keypair(
279        &self,
280        variant: &PostQuantumSignature,
281    ) -> Result<PostQuantumKeyPair> {
282        Err(anyhow!(
283            "Post-quantum key generation for {:?} requires the 'post-quantum' feature flag. \
284             Rebuild with: cargo build --features post-quantum",
285            variant
286        ))
287    }
288
289    /// Generate a SPHINCS+ key pair.
290    #[cfg(feature = "post-quantum")]
291    async fn generate_sphincs_keypair(
292        &self,
293        variant: &PostQuantumSignature,
294    ) -> Result<PostQuantumKeyPair> {
295        use pqcrypto_traits::sign::{PublicKey as _, SecretKey as _};
296        let (pk_bytes, sk_bytes) = match variant {
297            PostQuantumSignature::SphincsPlusSha2128s => {
298                let (pk, sk) = pqcrypto_sphincsplus::sphincssha2128ssimple::keypair();
299                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
300            }
301            PostQuantumSignature::SphincsPlusSha2128f => {
302                let (pk, sk) = pqcrypto_sphincsplus::sphincssha2128fsimple::keypair();
303                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
304            }
305            PostQuantumSignature::SphincsPlusSha2192s => {
306                let (pk, sk) = pqcrypto_sphincsplus::sphincssha2192ssimple::keypair();
307                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
308            }
309            PostQuantumSignature::SphincsPlusSha2192f => {
310                let (pk, sk) = pqcrypto_sphincsplus::sphincssha2192fsimple::keypair();
311                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
312            }
313            PostQuantumSignature::SphincsPlusSha2256s => {
314                let (pk, sk) = pqcrypto_sphincsplus::sphincssha2256ssimple::keypair();
315                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
316            }
317            PostQuantumSignature::SphincsPlusSha2256f => {
318                let (pk, sk) = pqcrypto_sphincsplus::sphincssha2256fsimple::keypair();
319                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
320            }
321            PostQuantumSignature::SphincsPlusShake128s => {
322                let (pk, sk) = pqcrypto_sphincsplus::sphincsshake128ssimple::keypair();
323                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
324            }
325            PostQuantumSignature::SphincsPlusShake128f => {
326                let (pk, sk) = pqcrypto_sphincsplus::sphincsshake128fsimple::keypair();
327                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
328            }
329            PostQuantumSignature::SphincsPlusShake192s => {
330                let (pk, sk) = pqcrypto_sphincsplus::sphincsshake192ssimple::keypair();
331                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
332            }
333            PostQuantumSignature::SphincsPlusShake192f => {
334                let (pk, sk) = pqcrypto_sphincsplus::sphincsshake192fsimple::keypair();
335                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
336            }
337            PostQuantumSignature::SphincsPlusShake256s => {
338                let (pk, sk) = pqcrypto_sphincsplus::sphincsshake256ssimple::keypair();
339                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
340            }
341            PostQuantumSignature::SphincsPlusShake256f => {
342                let (pk, sk) = pqcrypto_sphincsplus::sphincsshake256fsimple::keypair();
343                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
344            }
345            other => {
346                return Err(anyhow!(
347                    "generate_sphincs_keypair: unexpected variant {:?}",
348                    other
349                ))
350            }
351        };
352        Ok(PostQuantumKeyPair {
353            id: Uuid::new_v4().to_string(),
354            algorithm: variant.clone(),
355            public_key: pk_bytes,
356            private_key: sk_bytes,
357            created_at: Utc::now(),
358        })
359    }
360
361    #[cfg(not(feature = "post-quantum"))]
362    async fn generate_sphincs_keypair(
363        &self,
364        variant: &PostQuantumSignature,
365    ) -> Result<PostQuantumKeyPair> {
366        Err(anyhow!(
367            "Post-quantum key generation for {:?} requires the 'post-quantum' feature flag. \
368             Rebuild with: cargo build --features post-quantum",
369            variant
370        ))
371    }
372
373    /// Generate a Falcon key pair using pqcrypto-falcon.
374    ///
375    /// Supports Falcon512 and Falcon1024 variants. Requires the `post-quantum`
376    /// feature gate; returns a descriptive error otherwise.
377    #[cfg(feature = "post-quantum")]
378    async fn generate_falcon_keypair(
379        &self,
380        variant: &PostQuantumSignature,
381    ) -> Result<PostQuantumKeyPair> {
382        use pqcrypto_traits::sign::{PublicKey as _, SecretKey as _};
383        let (pk_bytes, sk_bytes) = match variant {
384            PostQuantumSignature::Falcon512 => {
385                let (pk, sk) = pqcrypto_falcon::falcon512::keypair();
386                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
387            }
388            PostQuantumSignature::Falcon1024 => {
389                let (pk, sk) = pqcrypto_falcon::falcon1024::keypair();
390                (pk.as_bytes().to_vec(), sk.as_bytes().to_vec())
391            }
392            other => {
393                return Err(anyhow!(
394                    "generate_falcon_keypair: unexpected variant {:?}",
395                    other
396                ))
397            }
398        };
399        Ok(PostQuantumKeyPair {
400            id: Uuid::new_v4().to_string(),
401            algorithm: variant.clone(),
402            public_key: pk_bytes,
403            private_key: sk_bytes,
404            created_at: Utc::now(),
405        })
406    }
407
408    #[cfg(not(feature = "post-quantum"))]
409    async fn generate_falcon_keypair(
410        &self,
411        variant: &PostQuantumSignature,
412    ) -> Result<PostQuantumKeyPair> {
413        Err(anyhow!(
414            "Falcon key generation for {:?} requires the 'post-quantum' feature flag. \
415             Rebuild with: cargo build --features post-quantum",
416            variant
417        ))
418    }
419
420    /// Sign `data` with Dilithium and return the raw detached signature bytes.
421    #[cfg(feature = "post-quantum")]
422    async fn dilithium_sign(
423        &self,
424        private_key: &[u8],
425        data: &[u8],
426        variant: &PostQuantumSignature,
427    ) -> Result<Vec<u8>> {
428        use pqcrypto_traits::sign::{DetachedSignature as _, SecretKey as _};
429        let sig_bytes = match variant {
430            PostQuantumSignature::Dilithium2 => {
431                let sk = pqcrypto_dilithium::dilithium2::SecretKey::from_bytes(private_key)
432                    .map_err(|e| anyhow!("Invalid Dilithium2 secret key: {}", e))?;
433                let sig = pqcrypto_dilithium::dilithium2::detached_sign(data, &sk);
434                sig.as_bytes().to_vec()
435            }
436            PostQuantumSignature::Dilithium3 => {
437                let sk = pqcrypto_dilithium::dilithium3::SecretKey::from_bytes(private_key)
438                    .map_err(|e| anyhow!("Invalid Dilithium3 secret key: {}", e))?;
439                let sig = pqcrypto_dilithium::dilithium3::detached_sign(data, &sk);
440                sig.as_bytes().to_vec()
441            }
442            PostQuantumSignature::Dilithium5 => {
443                let sk = pqcrypto_dilithium::dilithium5::SecretKey::from_bytes(private_key)
444                    .map_err(|e| anyhow!("Invalid Dilithium5 secret key: {}", e))?;
445                let sig = pqcrypto_dilithium::dilithium5::detached_sign(data, &sk);
446                sig.as_bytes().to_vec()
447            }
448            other => return Err(anyhow!("dilithium_sign: unexpected variant {:?}", other)),
449        };
450        Ok(sig_bytes)
451    }
452
453    #[cfg(not(feature = "post-quantum"))]
454    async fn dilithium_sign(
455        &self,
456        _private_key: &[u8],
457        _data: &[u8],
458        variant: &PostQuantumSignature,
459    ) -> Result<Vec<u8>> {
460        Err(anyhow!(
461            "Dilithium signing for {:?} requires the 'post-quantum' feature flag. \
462             Rebuild with: cargo build --features post-quantum",
463            variant
464        ))
465    }
466
467    /// Sign `data` with SPHINCS+ and return the raw detached signature bytes.
468    #[cfg(feature = "post-quantum")]
469    async fn sphincs_sign(
470        &self,
471        private_key: &[u8],
472        data: &[u8],
473        variant: &PostQuantumSignature,
474    ) -> Result<Vec<u8>> {
475        use pqcrypto_traits::sign::{DetachedSignature as _, SecretKey as _};
476        let sig_bytes = match variant {
477            PostQuantumSignature::SphincsPlusSha2128s => {
478                let sk =
479                    pqcrypto_sphincsplus::sphincssha2128ssimple::SecretKey::from_bytes(private_key)
480                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-128s secret key: {}", e))?;
481                pqcrypto_sphincsplus::sphincssha2128ssimple::detached_sign(data, &sk)
482                    .as_bytes()
483                    .to_vec()
484            }
485            PostQuantumSignature::SphincsPlusSha2128f => {
486                let sk =
487                    pqcrypto_sphincsplus::sphincssha2128fsimple::SecretKey::from_bytes(private_key)
488                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-128f secret key: {}", e))?;
489                pqcrypto_sphincsplus::sphincssha2128fsimple::detached_sign(data, &sk)
490                    .as_bytes()
491                    .to_vec()
492            }
493            PostQuantumSignature::SphincsPlusSha2192s => {
494                let sk =
495                    pqcrypto_sphincsplus::sphincssha2192ssimple::SecretKey::from_bytes(private_key)
496                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-192s secret key: {}", e))?;
497                pqcrypto_sphincsplus::sphincssha2192ssimple::detached_sign(data, &sk)
498                    .as_bytes()
499                    .to_vec()
500            }
501            PostQuantumSignature::SphincsPlusSha2192f => {
502                let sk =
503                    pqcrypto_sphincsplus::sphincssha2192fsimple::SecretKey::from_bytes(private_key)
504                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-192f secret key: {}", e))?;
505                pqcrypto_sphincsplus::sphincssha2192fsimple::detached_sign(data, &sk)
506                    .as_bytes()
507                    .to_vec()
508            }
509            PostQuantumSignature::SphincsPlusSha2256s => {
510                let sk =
511                    pqcrypto_sphincsplus::sphincssha2256ssimple::SecretKey::from_bytes(private_key)
512                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-256s secret key: {}", e))?;
513                pqcrypto_sphincsplus::sphincssha2256ssimple::detached_sign(data, &sk)
514                    .as_bytes()
515                    .to_vec()
516            }
517            PostQuantumSignature::SphincsPlusSha2256f => {
518                let sk =
519                    pqcrypto_sphincsplus::sphincssha2256fsimple::SecretKey::from_bytes(private_key)
520                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-256f secret key: {}", e))?;
521                pqcrypto_sphincsplus::sphincssha2256fsimple::detached_sign(data, &sk)
522                    .as_bytes()
523                    .to_vec()
524            }
525            PostQuantumSignature::SphincsPlusShake128s => {
526                let sk = pqcrypto_sphincsplus::sphincsshake128ssimple::SecretKey::from_bytes(
527                    private_key,
528                )
529                .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-128s secret key: {}", e))?;
530                pqcrypto_sphincsplus::sphincsshake128ssimple::detached_sign(data, &sk)
531                    .as_bytes()
532                    .to_vec()
533            }
534            PostQuantumSignature::SphincsPlusShake128f => {
535                let sk = pqcrypto_sphincsplus::sphincsshake128fsimple::SecretKey::from_bytes(
536                    private_key,
537                )
538                .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-128f secret key: {}", e))?;
539                pqcrypto_sphincsplus::sphincsshake128fsimple::detached_sign(data, &sk)
540                    .as_bytes()
541                    .to_vec()
542            }
543            PostQuantumSignature::SphincsPlusShake192s => {
544                let sk = pqcrypto_sphincsplus::sphincsshake192ssimple::SecretKey::from_bytes(
545                    private_key,
546                )
547                .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-192s secret key: {}", e))?;
548                pqcrypto_sphincsplus::sphincsshake192ssimple::detached_sign(data, &sk)
549                    .as_bytes()
550                    .to_vec()
551            }
552            PostQuantumSignature::SphincsPlusShake192f => {
553                let sk = pqcrypto_sphincsplus::sphincsshake192fsimple::SecretKey::from_bytes(
554                    private_key,
555                )
556                .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-192f secret key: {}", e))?;
557                pqcrypto_sphincsplus::sphincsshake192fsimple::detached_sign(data, &sk)
558                    .as_bytes()
559                    .to_vec()
560            }
561            PostQuantumSignature::SphincsPlusShake256s => {
562                let sk = pqcrypto_sphincsplus::sphincsshake256ssimple::SecretKey::from_bytes(
563                    private_key,
564                )
565                .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-256s secret key: {}", e))?;
566                pqcrypto_sphincsplus::sphincsshake256ssimple::detached_sign(data, &sk)
567                    .as_bytes()
568                    .to_vec()
569            }
570            PostQuantumSignature::SphincsPlusShake256f => {
571                let sk = pqcrypto_sphincsplus::sphincsshake256fsimple::SecretKey::from_bytes(
572                    private_key,
573                )
574                .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-256f secret key: {}", e))?;
575                pqcrypto_sphincsplus::sphincsshake256fsimple::detached_sign(data, &sk)
576                    .as_bytes()
577                    .to_vec()
578            }
579            other => return Err(anyhow!("sphincs_sign: unexpected variant {:?}", other)),
580        };
581        Ok(sig_bytes)
582    }
583
584    #[cfg(not(feature = "post-quantum"))]
585    async fn sphincs_sign(
586        &self,
587        _private_key: &[u8],
588        _data: &[u8],
589        variant: &PostQuantumSignature,
590    ) -> Result<Vec<u8>> {
591        Err(anyhow!(
592            "SPHINCS+ signing for {:?} requires the 'post-quantum' feature flag. \
593             Rebuild with: cargo build --features post-quantum",
594            variant
595        ))
596    }
597
598    /// Sign `data` with Falcon and return the raw detached signature bytes.
599    ///
600    /// Supports Falcon512 and Falcon1024. Requires the `post-quantum` feature gate.
601    #[cfg(feature = "post-quantum")]
602    async fn falcon_sign(
603        &self,
604        private_key: &[u8],
605        data: &[u8],
606        variant: &PostQuantumSignature,
607    ) -> Result<Vec<u8>> {
608        use pqcrypto_traits::sign::{DetachedSignature as _, SecretKey as _};
609        let sig_bytes = match variant {
610            PostQuantumSignature::Falcon512 => {
611                let sk = pqcrypto_falcon::falcon512::SecretKey::from_bytes(private_key)
612                    .map_err(|e| anyhow!("Invalid Falcon512 secret key: {}", e))?;
613                pqcrypto_falcon::falcon512::detached_sign(data, &sk)
614                    .as_bytes()
615                    .to_vec()
616            }
617            PostQuantumSignature::Falcon1024 => {
618                let sk = pqcrypto_falcon::falcon1024::SecretKey::from_bytes(private_key)
619                    .map_err(|e| anyhow!("Invalid Falcon1024 secret key: {}", e))?;
620                pqcrypto_falcon::falcon1024::detached_sign(data, &sk)
621                    .as_bytes()
622                    .to_vec()
623            }
624            other => return Err(anyhow!("falcon_sign: unexpected variant {:?}", other)),
625        };
626        Ok(sig_bytes)
627    }
628
629    #[cfg(not(feature = "post-quantum"))]
630    async fn falcon_sign(
631        &self,
632        _private_key: &[u8],
633        _data: &[u8],
634        variant: &PostQuantumSignature,
635    ) -> Result<Vec<u8>> {
636        Err(anyhow!(
637            "Falcon signing for {:?} requires the 'post-quantum' feature flag. \
638             Rebuild with: cargo build --features post-quantum",
639            variant
640        ))
641    }
642
643    /// Verify a Dilithium detached signature.
644    #[cfg(feature = "post-quantum")]
645    async fn dilithium_verify(
646        &self,
647        public_key: &[u8],
648        data: &[u8],
649        signature: &[u8],
650        variant: &PostQuantumSignature,
651    ) -> Result<bool> {
652        use pqcrypto_traits::sign::{DetachedSignature as _, PublicKey as _};
653        let ok = match variant {
654            PostQuantumSignature::Dilithium2 => {
655                let pk = pqcrypto_dilithium::dilithium2::PublicKey::from_bytes(public_key)
656                    .map_err(|e| anyhow!("Invalid Dilithium2 public key: {}", e))?;
657                let sig = pqcrypto_dilithium::dilithium2::DetachedSignature::from_bytes(signature)
658                    .map_err(|e| anyhow!("Invalid Dilithium2 signature: {}", e))?;
659                pqcrypto_dilithium::dilithium2::verify_detached_signature(&sig, data, &pk).is_ok()
660            }
661            PostQuantumSignature::Dilithium3 => {
662                let pk = pqcrypto_dilithium::dilithium3::PublicKey::from_bytes(public_key)
663                    .map_err(|e| anyhow!("Invalid Dilithium3 public key: {}", e))?;
664                let sig = pqcrypto_dilithium::dilithium3::DetachedSignature::from_bytes(signature)
665                    .map_err(|e| anyhow!("Invalid Dilithium3 signature: {}", e))?;
666                pqcrypto_dilithium::dilithium3::verify_detached_signature(&sig, data, &pk).is_ok()
667            }
668            PostQuantumSignature::Dilithium5 => {
669                let pk = pqcrypto_dilithium::dilithium5::PublicKey::from_bytes(public_key)
670                    .map_err(|e| anyhow!("Invalid Dilithium5 public key: {}", e))?;
671                let sig = pqcrypto_dilithium::dilithium5::DetachedSignature::from_bytes(signature)
672                    .map_err(|e| anyhow!("Invalid Dilithium5 signature: {}", e))?;
673                pqcrypto_dilithium::dilithium5::verify_detached_signature(&sig, data, &pk).is_ok()
674            }
675            other => return Err(anyhow!("dilithium_verify: unexpected variant {:?}", other)),
676        };
677        Ok(ok)
678    }
679
680    #[cfg(not(feature = "post-quantum"))]
681    async fn dilithium_verify(
682        &self,
683        _public_key: &[u8],
684        _data: &[u8],
685        _signature: &[u8],
686        variant: &PostQuantumSignature,
687    ) -> Result<bool> {
688        Err(anyhow!(
689            "Dilithium verification for {:?} requires the 'post-quantum' feature flag. \
690             Rebuild with: cargo build --features post-quantum",
691            variant
692        ))
693    }
694
695    /// Verify a SPHINCS+ detached signature.
696    #[cfg(feature = "post-quantum")]
697    async fn sphincs_verify(
698        &self,
699        public_key: &[u8],
700        data: &[u8],
701        signature: &[u8],
702        variant: &PostQuantumSignature,
703    ) -> Result<bool> {
704        use pqcrypto_traits::sign::{DetachedSignature as _, PublicKey as _};
705        let ok = match variant {
706            PostQuantumSignature::SphincsPlusSha2128s => {
707                let pk =
708                    pqcrypto_sphincsplus::sphincssha2128ssimple::PublicKey::from_bytes(public_key)
709                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-128s public key: {}", e))?;
710                let sig =
711                    pqcrypto_sphincsplus::sphincssha2128ssimple::DetachedSignature::from_bytes(
712                        signature,
713                    )
714                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-128s signature: {}", e))?;
715                pqcrypto_sphincsplus::sphincssha2128ssimple::verify_detached_signature(
716                    &sig, data, &pk,
717                )
718                .is_ok()
719            }
720            PostQuantumSignature::SphincsPlusSha2128f => {
721                let pk =
722                    pqcrypto_sphincsplus::sphincssha2128fsimple::PublicKey::from_bytes(public_key)
723                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-128f public key: {}", e))?;
724                let sig =
725                    pqcrypto_sphincsplus::sphincssha2128fsimple::DetachedSignature::from_bytes(
726                        signature,
727                    )
728                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-128f signature: {}", e))?;
729                pqcrypto_sphincsplus::sphincssha2128fsimple::verify_detached_signature(
730                    &sig, data, &pk,
731                )
732                .is_ok()
733            }
734            PostQuantumSignature::SphincsPlusSha2192s => {
735                let pk =
736                    pqcrypto_sphincsplus::sphincssha2192ssimple::PublicKey::from_bytes(public_key)
737                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-192s public key: {}", e))?;
738                let sig =
739                    pqcrypto_sphincsplus::sphincssha2192ssimple::DetachedSignature::from_bytes(
740                        signature,
741                    )
742                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-192s signature: {}", e))?;
743                pqcrypto_sphincsplus::sphincssha2192ssimple::verify_detached_signature(
744                    &sig, data, &pk,
745                )
746                .is_ok()
747            }
748            PostQuantumSignature::SphincsPlusSha2192f => {
749                let pk =
750                    pqcrypto_sphincsplus::sphincssha2192fsimple::PublicKey::from_bytes(public_key)
751                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-192f public key: {}", e))?;
752                let sig =
753                    pqcrypto_sphincsplus::sphincssha2192fsimple::DetachedSignature::from_bytes(
754                        signature,
755                    )
756                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-192f signature: {}", e))?;
757                pqcrypto_sphincsplus::sphincssha2192fsimple::verify_detached_signature(
758                    &sig, data, &pk,
759                )
760                .is_ok()
761            }
762            PostQuantumSignature::SphincsPlusSha2256s => {
763                let pk =
764                    pqcrypto_sphincsplus::sphincssha2256ssimple::PublicKey::from_bytes(public_key)
765                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-256s public key: {}", e))?;
766                let sig =
767                    pqcrypto_sphincsplus::sphincssha2256ssimple::DetachedSignature::from_bytes(
768                        signature,
769                    )
770                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-256s signature: {}", e))?;
771                pqcrypto_sphincsplus::sphincssha2256ssimple::verify_detached_signature(
772                    &sig, data, &pk,
773                )
774                .is_ok()
775            }
776            PostQuantumSignature::SphincsPlusSha2256f => {
777                let pk =
778                    pqcrypto_sphincsplus::sphincssha2256fsimple::PublicKey::from_bytes(public_key)
779                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-256f public key: {}", e))?;
780                let sig =
781                    pqcrypto_sphincsplus::sphincssha2256fsimple::DetachedSignature::from_bytes(
782                        signature,
783                    )
784                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHA2-256f signature: {}", e))?;
785                pqcrypto_sphincsplus::sphincssha2256fsimple::verify_detached_signature(
786                    &sig, data, &pk,
787                )
788                .is_ok()
789            }
790            PostQuantumSignature::SphincsPlusShake128s => {
791                let pk =
792                    pqcrypto_sphincsplus::sphincsshake128ssimple::PublicKey::from_bytes(public_key)
793                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-128s public key: {}", e))?;
794                let sig =
795                    pqcrypto_sphincsplus::sphincsshake128ssimple::DetachedSignature::from_bytes(
796                        signature,
797                    )
798                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-128s signature: {}", e))?;
799                pqcrypto_sphincsplus::sphincsshake128ssimple::verify_detached_signature(
800                    &sig, data, &pk,
801                )
802                .is_ok()
803            }
804            PostQuantumSignature::SphincsPlusShake128f => {
805                let pk =
806                    pqcrypto_sphincsplus::sphincsshake128fsimple::PublicKey::from_bytes(public_key)
807                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-128f public key: {}", e))?;
808                let sig =
809                    pqcrypto_sphincsplus::sphincsshake128fsimple::DetachedSignature::from_bytes(
810                        signature,
811                    )
812                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-128f signature: {}", e))?;
813                pqcrypto_sphincsplus::sphincsshake128fsimple::verify_detached_signature(
814                    &sig, data, &pk,
815                )
816                .is_ok()
817            }
818            PostQuantumSignature::SphincsPlusShake192s => {
819                let pk =
820                    pqcrypto_sphincsplus::sphincsshake192ssimple::PublicKey::from_bytes(public_key)
821                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-192s public key: {}", e))?;
822                let sig =
823                    pqcrypto_sphincsplus::sphincsshake192ssimple::DetachedSignature::from_bytes(
824                        signature,
825                    )
826                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-192s signature: {}", e))?;
827                pqcrypto_sphincsplus::sphincsshake192ssimple::verify_detached_signature(
828                    &sig, data, &pk,
829                )
830                .is_ok()
831            }
832            PostQuantumSignature::SphincsPlusShake192f => {
833                let pk =
834                    pqcrypto_sphincsplus::sphincsshake192fsimple::PublicKey::from_bytes(public_key)
835                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-192f public key: {}", e))?;
836                let sig =
837                    pqcrypto_sphincsplus::sphincsshake192fsimple::DetachedSignature::from_bytes(
838                        signature,
839                    )
840                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-192f signature: {}", e))?;
841                pqcrypto_sphincsplus::sphincsshake192fsimple::verify_detached_signature(
842                    &sig, data, &pk,
843                )
844                .is_ok()
845            }
846            PostQuantumSignature::SphincsPlusShake256s => {
847                let pk =
848                    pqcrypto_sphincsplus::sphincsshake256ssimple::PublicKey::from_bytes(public_key)
849                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-256s public key: {}", e))?;
850                let sig =
851                    pqcrypto_sphincsplus::sphincsshake256ssimple::DetachedSignature::from_bytes(
852                        signature,
853                    )
854                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-256s signature: {}", e))?;
855                pqcrypto_sphincsplus::sphincsshake256ssimple::verify_detached_signature(
856                    &sig, data, &pk,
857                )
858                .is_ok()
859            }
860            PostQuantumSignature::SphincsPlusShake256f => {
861                let pk =
862                    pqcrypto_sphincsplus::sphincsshake256fsimple::PublicKey::from_bytes(public_key)
863                        .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-256f public key: {}", e))?;
864                let sig =
865                    pqcrypto_sphincsplus::sphincsshake256fsimple::DetachedSignature::from_bytes(
866                        signature,
867                    )
868                    .map_err(|e| anyhow!("Invalid SPHINCS+ SHAKE-256f signature: {}", e))?;
869                pqcrypto_sphincsplus::sphincsshake256fsimple::verify_detached_signature(
870                    &sig, data, &pk,
871                )
872                .is_ok()
873            }
874            other => return Err(anyhow!("sphincs_verify: unexpected variant {:?}", other)),
875        };
876        Ok(ok)
877    }
878
879    #[cfg(not(feature = "post-quantum"))]
880    async fn sphincs_verify(
881        &self,
882        _public_key: &[u8],
883        _data: &[u8],
884        _signature: &[u8],
885        variant: &PostQuantumSignature,
886    ) -> Result<bool> {
887        Err(anyhow!(
888            "SPHINCS+ verification for {:?} requires the 'post-quantum' feature flag. \
889             Rebuild with: cargo build --features post-quantum",
890            variant
891        ))
892    }
893
894    /// Verify a Falcon detached signature.
895    ///
896    /// Supports Falcon512 and Falcon1024. Requires the `post-quantum` feature gate.
897    #[cfg(feature = "post-quantum")]
898    async fn falcon_verify(
899        &self,
900        public_key: &[u8],
901        data: &[u8],
902        signature: &[u8],
903        variant: &PostQuantumSignature,
904    ) -> Result<bool> {
905        use pqcrypto_traits::sign::{DetachedSignature as _, PublicKey as _};
906        let ok = match variant {
907            PostQuantumSignature::Falcon512 => {
908                let pk = pqcrypto_falcon::falcon512::PublicKey::from_bytes(public_key)
909                    .map_err(|e| anyhow!("Invalid Falcon512 public key: {}", e))?;
910                let sig = pqcrypto_falcon::falcon512::DetachedSignature::from_bytes(signature)
911                    .map_err(|e| anyhow!("Invalid Falcon512 signature: {}", e))?;
912                pqcrypto_falcon::falcon512::verify_detached_signature(&sig, data, &pk).is_ok()
913            }
914            PostQuantumSignature::Falcon1024 => {
915                let pk = pqcrypto_falcon::falcon1024::PublicKey::from_bytes(public_key)
916                    .map_err(|e| anyhow!("Invalid Falcon1024 public key: {}", e))?;
917                let sig = pqcrypto_falcon::falcon1024::DetachedSignature::from_bytes(signature)
918                    .map_err(|e| anyhow!("Invalid Falcon1024 signature: {}", e))?;
919                pqcrypto_falcon::falcon1024::verify_detached_signature(&sig, data, &pk).is_ok()
920            }
921            other => return Err(anyhow!("falcon_verify: unexpected variant {:?}", other)),
922        };
923        Ok(ok)
924    }
925
926    #[cfg(not(feature = "post-quantum"))]
927    async fn falcon_verify(
928        &self,
929        _public_key: &[u8],
930        _data: &[u8],
931        _signature: &[u8],
932        variant: &PostQuantumSignature,
933    ) -> Result<bool> {
934        Err(anyhow!(
935            "Falcon signature verification for {:?} requires the 'post-quantum' feature flag. \
936             Rebuild with: cargo build --features post-quantum",
937            variant
938        ))
939    }
940
941    /// Encapsulate a shared secret using Kyber KEM.
942    ///
943    /// Returns `(ciphertext, shared_secret)`. Enable the `post-quantum` feature
944    /// for a real cryptographic implementation.
945    #[cfg(feature = "post-quantum")]
946    async fn kyber_encapsulate(&self, public_key: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
947        use pqcrypto_traits::kem::{Ciphertext as _, PublicKey as _, SharedSecret as _};
948        let pk = pqcrypto_kyber::kyber768::PublicKey::from_bytes(public_key)
949            .map_err(|e| anyhow!("Invalid Kyber768 public key: {}", e))?;
950        let (ss, ct) = pqcrypto_kyber::kyber768::encapsulate(&pk);
951        Ok((ct.as_bytes().to_vec(), ss.as_bytes().to_vec()))
952    }
953
954    #[cfg(not(feature = "post-quantum"))]
955    async fn kyber_encapsulate(&self, _public_key: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
956        Err(anyhow!(
957            "Kyber KEM encapsulation requires the 'post-quantum' feature flag. \
958             Rebuild with: cargo build --features post-quantum"
959        ))
960    }
961
962    /// Encapsulate a shared secret using NewHope.
963    ///
964    /// No pure-Rust or pqcrypto crate for NewHope is available; returns an
965    /// informative error.
966    async fn newhope_encapsulate(&self, _public_key: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
967        Err(anyhow!(
968            "NewHope KEM encapsulation is not yet supported. \
969             No pqcrypto crate for NewHope is currently available."
970        ))
971    }
972
973    /// Encapsulate a shared secret using FrodoKEM.
974    ///
975    /// No pure-Rust or pqcrypto crate for FrodoKEM is available; returns an
976    /// informative error.
977    async fn frodokem_encapsulate(&self, _public_key: &[u8]) -> Result<(Vec<u8>, Vec<u8>)> {
978        Err(anyhow!(
979            "FrodoKEM encapsulation is not yet supported. \
980             No pqcrypto crate for FrodoKEM is currently available."
981        ))
982    }
983
984    /// Decapsulate using Kyber KEM, returning the shared secret.
985    #[cfg(feature = "post-quantum")]
986    async fn kyber_decapsulate(&self, private_key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>> {
987        use pqcrypto_traits::kem::{Ciphertext as _, SecretKey as _, SharedSecret as _};
988        let sk = pqcrypto_kyber::kyber768::SecretKey::from_bytes(private_key)
989            .map_err(|e| anyhow!("Invalid Kyber768 secret key: {}", e))?;
990        let ct = pqcrypto_kyber::kyber768::Ciphertext::from_bytes(ciphertext)
991            .map_err(|e| anyhow!("Invalid Kyber768 ciphertext: {}", e))?;
992        let ss = pqcrypto_kyber::kyber768::decapsulate(&ct, &sk);
993        Ok(ss.as_bytes().to_vec())
994    }
995
996    #[cfg(not(feature = "post-quantum"))]
997    async fn kyber_decapsulate(&self, _private_key: &[u8], _ciphertext: &[u8]) -> Result<Vec<u8>> {
998        Err(anyhow!(
999            "Kyber KEM decapsulation requires the 'post-quantum' feature flag. \
1000             Rebuild with: cargo build --features post-quantum"
1001        ))
1002    }
1003
1004    /// Decapsulate using NewHope. Returns an error (not yet supported).
1005    async fn newhope_decapsulate(
1006        &self,
1007        _private_key: &[u8],
1008        _ciphertext: &[u8],
1009    ) -> Result<Vec<u8>> {
1010        Err(anyhow!(
1011            "NewHope KEM decapsulation is not yet supported. \
1012             No pqcrypto crate for NewHope is currently available."
1013        ))
1014    }
1015
1016    /// Decapsulate using FrodoKEM. Returns an error (not yet supported).
1017    async fn frodokem_decapsulate(
1018        &self,
1019        _private_key: &[u8],
1020        _ciphertext: &[u8],
1021    ) -> Result<Vec<u8>> {
1022        Err(anyhow!(
1023            "FrodoKEM decapsulation is not yet supported. \
1024             No pqcrypto crate for FrodoKEM is currently available."
1025        ))
1026    }
1027
1028    /// Get current metrics
1029    pub async fn get_metrics(&self) -> PQCryptoMetrics {
1030        self.metrics.read().await.clone()
1031    }
1032}
1033
1034/// Post-quantum key pair
1035#[derive(Debug, Clone, Serialize, Deserialize)]
1036pub struct PostQuantumKeyPair {
1037    pub id: String,
1038    pub algorithm: PostQuantumSignature,
1039    pub public_key: Vec<u8>,
1040    pub private_key: Vec<u8>,
1041    pub created_at: DateTime<Utc>,
1042}
1043
1044/// Signature information for caching
1045#[derive(Debug, Clone)]
1046struct SignatureInfo {
1047    #[allow(dead_code)]
1048    signature: Vec<u8>,
1049    #[allow(dead_code)]
1050    algorithm: PostQuantumSignature,
1051    #[allow(dead_code)]
1052    created_at: DateTime<Utc>,
1053}
1054
1055/// Post-quantum cryptography metrics
1056#[derive(Debug, Clone, Default)]
1057pub struct PQCryptoMetrics {
1058    pub key_generation_count: u64,
1059    pub signature_count: u64,
1060    pub verification_count: u64,
1061    pub successful_verifications: u64,
1062    pub avg_key_generation_time_ms: f64,
1063    pub avg_signing_time_ms: f64,
1064    pub avg_verification_time_ms: f64,
1065    pub encapsulation_count: u64,
1066    pub decapsulation_count: u64,
1067    pub avg_encapsulation_time_ms: f64,
1068    pub avg_decapsulation_time_ms: f64,
1069}