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: saorsalabs@gmail.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 hybrid;
22// Legacy modules deprecated - use ant-quic PQC functions directly
23// pub mod ml_dsa;
24// pub mod ml_kem;
25pub mod types;
26pub mod ant_quic_integration;
27
28// NOTE: Not using wildcard import to avoid conflicts with ant-quic types
29// Selectively re-export only non-conflicting types from our types module
30pub use self::types::{
31    GroupId, ParticipantId, PeerId, SessionId, QuantumPeerIdentity, 
32    SecureSession, SessionState, HandshakeParameters, HybridSignature,
33    Ed25519PublicKey, Ed25519PrivateKey, Ed25519Signature,
34    FrostPublicKey, FrostGroupPublicKey, FrostKeyShare, FrostCommitment, FrostSignature,
35};
36
37// Re-export all ant-quic PQC functions for convenience
38pub use self::ant_quic_integration::{
39    // Configuration functions
40    create_default_pqc_config, create_pqc_only_config,
41    // ML-DSA functions
42    generate_ml_dsa_keypair, ml_dsa_sign, ml_dsa_verify,
43    // ML-KEM functions  
44    generate_ml_kem_keypair, ml_kem_encapsulate, ml_kem_decapsulate,
45    // Hybrid functions
46    generate_hybrid_kem_keypair, hybrid_kem_encapsulate, hybrid_kem_decapsulate,
47    generate_hybrid_signature_keypair, hybrid_sign, hybrid_verify,
48    // Performance optimization
49    create_pqc_memory_pool,
50};
51
52
53use serde::{Deserialize, Serialize};
54use thiserror::Error;
55
56/// Quantum cryptography errors
57#[derive(Debug, Error)]
58pub enum QuantumCryptoError {
59    #[error("ML-KEM error: {0}")]
60    MlKemError(String),
61
62    #[error("ML-DSA error: {0}")]
63    MlDsaError(String),
64
65    #[error("Key generation failed: {0}")]
66    KeyGenerationError(String),
67
68    #[error("Invalid key material: {0}")]
69    InvalidKeyError(String),
70
71    #[error("Signature verification failed")]
72    SignatureVerificationFailed,
73
74    #[error("Encapsulation failed: {0}")]
75    EncapsulationError(String),
76
77    #[error("Decapsulation failed: {0}")]
78    DecapsulationError(String),
79
80    #[error("Unsupported algorithm: {0}")]
81    UnsupportedAlgorithm(String),
82}
83
84/// Result type for quantum crypto operations
85pub type Result<T> = std::result::Result<T, QuantumCryptoError>;
86
87/// Cryptographic algorithm capabilities
88#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
89pub struct CryptoCapabilities {
90    pub supports_ml_kem: bool,
91    pub supports_ml_dsa: bool,
92    pub supports_frost: bool,
93    pub supports_hybrid: bool,
94    pub threshold_capable: bool,
95    pub supported_versions: Vec<ProtocolVersion>,
96}
97
98impl Default for CryptoCapabilities {
99    fn default() -> Self {
100        Self {
101            supports_ml_kem: true,
102            supports_ml_dsa: true,
103            supports_frost: true,
104            supports_hybrid: true,
105            threshold_capable: true,
106            supported_versions: vec![ProtocolVersion::V1, ProtocolVersion::V2],
107        }
108    }
109}
110
111/// Protocol version for algorithm negotiation
112#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
113pub enum ProtocolVersion {
114    /// Initial version with ML-KEM-768 and ML-DSA-65
115    V1,
116    /// Enhanced version with additional algorithms
117    V2,
118}
119
120/// Signature scheme selection
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub enum SignatureScheme {
123    /// Classical Ed25519 signatures (for backward compatibility)
124    Classical(Vec<u8>),
125
126    /// Post-quantum ML-DSA signatures
127    PostQuantum(Vec<u8>),
128
129    /// Dual signatures for hybrid mode
130    Dual {
131        classical: Vec<u8>,
132        post_quantum: Vec<u8>,
133    },
134}
135
136// NOTE: SignatureScheme::verify method removed - use ant-quic PQC verify functions directly:
137// - ml_dsa_verify(public_key: &MlDsaPublicKey, message: &[u8], signature: &MlDsaSignature)
138// - For Ed25519: use ed25519_verify from this module
139// These are re-exported from ant_quic_integration module
140
141impl SignatureScheme {
142    // verify method removed - see note above
143}
144
145// NOTE: PublicKeySet and PrivateKeySet removed - use ant-quic PQC types directly
146
147// NOTE: KeyPair struct and generate_keypair function removed to avoid conflicts
148// Use ant-quic PQC functions directly:
149// - generate_ml_dsa_keypair() -> (MlDsaPublicKey, MlDsaSecretKey)
150// - generate_ml_kem_keypair() -> (MlKemPublicKey, MlKemSecretKey) 
151// - For Ed25519: generate_ed25519_keypair() below
152//
153// These functions are re-exported from ant_quic_integration module
154
155/// Generate Ed25519 keypair (placeholder for actual implementation)
156fn generate_ed25519_keypair() -> Result<(Vec<u8>, Vec<u8>)> {
157    use ed25519_dalek::SigningKey;
158    use rand::rngs::OsRng;
159
160    let signing_key = SigningKey::generate(&mut OsRng);
161    let public_key = signing_key.verifying_key().to_bytes().to_vec();
162
163    // Create 64-byte private key (signing key + public key)
164    let mut private_key = vec![0u8; 64];
165    private_key[..32].copy_from_slice(&signing_key.to_bytes());
166    private_key[32..].copy_from_slice(&public_key);
167
168    Ok((public_key, private_key))
169}
170
171/// Algorithm negotiation for establishing connections
172pub fn negotiate_algorithms(
173    local_caps: &CryptoCapabilities,
174    remote_caps: &CryptoCapabilities,
175) -> Result<NegotiatedAlgorithms> {
176    // Find common supported algorithms
177    let use_ml_kem = local_caps.supports_ml_kem && remote_caps.supports_ml_kem;
178    let use_ml_dsa = local_caps.supports_ml_dsa && remote_caps.supports_ml_dsa;
179    let use_hybrid = local_caps.supports_hybrid && remote_caps.supports_hybrid;
180
181    // Find common protocol version
182    let version = local_caps
183        .supported_versions
184        .iter()
185        .find(|v| remote_caps.supported_versions.contains(v))
186        .copied()
187        .ok_or_else(|| {
188            QuantumCryptoError::UnsupportedAlgorithm("No common protocol version".to_string())
189        })?;
190
191    Ok(NegotiatedAlgorithms {
192        kem_algorithm: if use_ml_kem {
193            KemAlgorithm::MlKem768
194        } else {
195            KemAlgorithm::ClassicalEcdh
196        },
197        signature_algorithm: if use_ml_dsa {
198            SignatureAlgorithm::MlDsa65
199        } else {
200            SignatureAlgorithm::Ed25519
201        },
202        hybrid_mode: use_hybrid,
203        protocol_version: version,
204    })
205}
206
207/// Negotiated algorithm set
208#[derive(Debug, Clone, Serialize, Deserialize)]
209pub struct NegotiatedAlgorithms {
210    pub kem_algorithm: KemAlgorithm,
211    pub signature_algorithm: SignatureAlgorithm,
212    pub hybrid_mode: bool,
213    pub protocol_version: ProtocolVersion,
214}
215
216/// Key encapsulation mechanism algorithm
217#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
218pub enum KemAlgorithm {
219    MlKem768,
220    ClassicalEcdh,
221}
222
223/// Signature algorithm
224#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
225pub enum SignatureAlgorithm {
226    MlDsa65,
227    Ed25519,
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[tokio::test]
235    async fn test_keypair_generation() {
236        // NOTE: Legacy test deprecated - use ant-quic PQC functions directly:
237        // - generate_ml_dsa_keypair() -> (MlDsaPublicKey, MlDsaSecretKey)
238        // - generate_ml_kem_keypair() -> (MlKemPublicKey, MlKemSecretKey)
239        let _caps = CryptoCapabilities::default();
240        // Test deprecated - would need significant rewrite for ant-quic types
241    }
242
243    #[test]
244    fn test_algorithm_negotiation() {
245        let local_caps = CryptoCapabilities::default();
246        let remote_caps = CryptoCapabilities {
247            supports_ml_kem: true,
248            supports_ml_dsa: false,
249            supports_frost: false,
250            supports_hybrid: true,
251            threshold_capable: false,
252            supported_versions: vec![ProtocolVersion::V1],
253        };
254
255        let negotiated = negotiate_algorithms(&local_caps, &remote_caps).unwrap();
256        assert_eq!(negotiated.kem_algorithm, KemAlgorithm::MlKem768);
257        assert_eq!(negotiated.signature_algorithm, SignatureAlgorithm::Ed25519);
258        assert!(negotiated.hybrid_mode);
259    }
260}