saorsa_core/quantum_crypto/
mod.rs

1// Copyright 2024 Saorsa Labs Limited
2//
3// This software is dual-licensed under:
4// - GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later)
5// - Commercial License
6//
7// For AGPL-3.0 license, see LICENSE-AGPL-3.0
8// For commercial licensing, contact: david@saorsalabs.com
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under these licenses is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
14//! Quantum-resistant cryptography module
15//!
16//! This module provides post-quantum cryptographic primitives including:
17//! - ML-KEM (Module-Lattice Key Encapsulation Mechanism) for key exchange
18//! - ML-DSA (Module-Lattice Digital Signature Algorithm) for signatures
19//! - Hybrid modes for gradual migration from classical algorithms
20
21pub mod ant_quic_integration;
22pub mod types;
23
24// NOTE: Not using wildcard import to avoid conflicts with ant-quic types
25// Selectively re-export only non-conflicting types from our types module
26pub use self::types::{
27    FrostCommitment, FrostGroupPublicKey, FrostKeyShare, FrostPublicKey, FrostSignature, GroupId,
28    HandshakeParameters, ParticipantId, PeerId, QuantumPeerIdentity, SecureSession, SessionId,
29    SessionState,
30};
31
32// Re-export all ant-quic PQC functions for convenience
33pub use self::ant_quic_integration::{
34    // Configuration functions
35    create_default_pqc_config,
36    // Performance optimization
37    create_pqc_memory_pool,
38    create_pqc_only_config,
39    // Hybrid functions
40    generate_hybrid_kem_keypair,
41    generate_hybrid_signature_keypair,
42    // ML-DSA functions
43    generate_ml_dsa_keypair,
44    // ML-KEM functions
45    generate_ml_kem_keypair,
46    hybrid_kem_decapsulate,
47    hybrid_kem_encapsulate,
48    hybrid_sign,
49    hybrid_verify,
50    ml_dsa_sign,
51    ml_dsa_verify,
52    ml_kem_decapsulate,
53    ml_kem_encapsulate,
54};
55
56use serde::{Deserialize, Serialize};
57use thiserror::Error;
58
59// Primary post-quantum cryptography types from saorsa-pqc 0.3.0
60pub use saorsa_pqc::{
61    // Symmetric encryption (quantum-resistant)
62    ChaCha20Poly1305Cipher,
63    // Encrypted message types
64    EncryptedMessage,
65    // Hybrid APIs (optional)
66    HybridKem,
67    HybridPublicKeyEncryption,
68    MlDsa65,
69
70    MlDsaOperations,
71
72    // Algorithm implementations
73    MlKem768,
74    // Core traits for operations
75    MlKemOperations,
76    SymmetricEncryptedMessage,
77
78    // Errors
79    SymmetricError,
80
81    SymmetricKey,
82
83    // Library initialization
84    init as saorsa_pqc_init,
85    // Types and results
86    pqc::types::{
87        HybridKemCiphertext, HybridKemPublicKey, HybridKemSecretKey, HybridSignaturePublicKey,
88        HybridSignatureSecretKey, HybridSignatureValue, MlDsaPublicKey, MlDsaSecretKey,
89        MlDsaSignature, MlKemCiphertext, MlKemPublicKey, MlKemSecretKey, PqcError,
90        PqcResult as SaorsaPqcResult, SharedSecret,
91    },
92};
93
94/// Quantum cryptography errors
95#[derive(Debug, Error)]
96pub enum QuantumCryptoError {
97    #[error("ML-KEM error: {0}")]
98    MlKemError(String),
99
100    #[error("ML-DSA error: {0}")]
101    MlDsaError(String),
102
103    #[error("Key generation failed: {0}")]
104    KeyGenerationError(String),
105
106    #[error("Invalid key material: {0}")]
107    InvalidKeyError(String),
108
109    #[error("Signature verification failed")]
110    SignatureVerificationFailed,
111
112    #[error("Encapsulation failed: {0}")]
113    EncapsulationError(String),
114
115    #[error("Decapsulation failed: {0}")]
116    DecapsulationError(String),
117
118    #[error("Unsupported algorithm: {0}")]
119    UnsupportedAlgorithm(String),
120}
121
122/// Result type for quantum crypto operations
123pub type Result<T> = std::result::Result<T, QuantumCryptoError>;
124
125/// Cryptographic algorithm capabilities
126#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
127pub struct CryptoCapabilities {
128    pub supports_ml_kem: bool,
129    pub supports_ml_dsa: bool,
130    pub supports_frost: bool,
131    pub supports_hybrid: bool,
132    pub threshold_capable: bool,
133    pub supported_versions: Vec<ProtocolVersion>,
134}
135
136impl Default for CryptoCapabilities {
137    fn default() -> Self {
138        Self {
139            supports_ml_kem: true,
140            supports_ml_dsa: true,
141            supports_frost: true,
142            supports_hybrid: true,
143            threshold_capable: true,
144            supported_versions: vec![ProtocolVersion::V1, ProtocolVersion::V2],
145        }
146    }
147}
148
149/// Protocol version for algorithm negotiation
150#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
151pub enum ProtocolVersion {
152    /// Initial version with ML-KEM-768 and ML-DSA-65
153    V1,
154    /// Enhanced version with additional algorithms
155    V2,
156}
157
158// PQC-only; hybrid and classical paths removed
159
160/// Algorithm negotiation for establishing connections
161pub fn negotiate_algorithms(
162    local_caps: &CryptoCapabilities,
163    remote_caps: &CryptoCapabilities,
164) -> Result<NegotiatedAlgorithms> {
165    // Find common supported algorithms
166    let use_ml_kem = local_caps.supports_ml_kem && remote_caps.supports_ml_kem;
167    let use_ml_dsa = local_caps.supports_ml_dsa && remote_caps.supports_ml_dsa;
168    let use_hybrid = local_caps.supports_hybrid && remote_caps.supports_hybrid;
169
170    // Find common protocol version
171    let version = local_caps
172        .supported_versions
173        .iter()
174        .find(|v| remote_caps.supported_versions.contains(v))
175        .copied()
176        .ok_or_else(|| {
177            QuantumCryptoError::UnsupportedAlgorithm("No common protocol version".to_string())
178        })?;
179
180    // Select algorithms based on negotiated capabilities
181    let kem_algorithm = if use_ml_kem {
182        KemAlgorithm::MlKem768
183    } else {
184        return Err(QuantumCryptoError::UnsupportedAlgorithm(
185            "No common KEM algorithm".to_string(),
186        ));
187    };
188
189    let signature_algorithm = if use_ml_dsa {
190        SignatureAlgorithm::MlDsa65
191    } else {
192        return Err(QuantumCryptoError::UnsupportedAlgorithm(
193            "No common signature algorithm".to_string(),
194        ));
195    };
196
197    Ok(NegotiatedAlgorithms {
198        kem_algorithm,
199        signature_algorithm,
200        hybrid_mode: use_hybrid,
201        protocol_version: version,
202    })
203}
204
205/// Negotiated algorithm set
206#[derive(Debug, Clone, Serialize, Deserialize)]
207pub struct NegotiatedAlgorithms {
208    pub kem_algorithm: KemAlgorithm,
209    pub signature_algorithm: SignatureAlgorithm,
210    pub hybrid_mode: bool,
211    pub protocol_version: ProtocolVersion,
212}
213
214/// Key encapsulation mechanism algorithm
215#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
216pub enum KemAlgorithm {
217    MlKem768,
218}
219
220/// Signature algorithm
221#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
222pub enum SignatureAlgorithm {
223    MlDsa65,
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[test]
231    fn test_saorsa_pqc_availability() {
232        // Test that saorsa-pqc types are available and can be instantiated
233        let _ml_kem = MlKem768;
234        let _ml_dsa = MlDsa65;
235        let _hybrid_kem = HybridKem::default();
236        // HybridSignatureValue doesn't implement Default - skip
237        let _hybrid_pke = HybridPublicKeyEncryption::default();
238
239        println!("✅ saorsa-pqc 0.3.0 types are available");
240        println!("✅ Confirmed we are using saorsa-pqc effectively");
241        println!("✅ ChaCha20Poly1305 integration ready for use");
242    }
243
244    #[test]
245    fn test_algorithm_negotiation() {
246        let local_caps = CryptoCapabilities::default();
247        let remote_caps = CryptoCapabilities {
248            supports_ml_kem: true,
249            supports_ml_dsa: true,
250            supports_frost: false,
251            supports_hybrid: true,
252            threshold_capable: false,
253            supported_versions: vec![ProtocolVersion::V1],
254        };
255
256        let negotiated = negotiate_algorithms(&local_caps, &remote_caps).unwrap();
257        assert_eq!(negotiated.kem_algorithm, KemAlgorithm::MlKem768);
258        assert_eq!(negotiated.signature_algorithm, SignatureAlgorithm::MlDsa65);
259    }
260}