Skip to main content

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
20pub mod ant_quic_integration;
21pub mod types;
22
23// NOTE: Not using wildcard import to avoid conflicts with ant-quic types
24// Selectively re-export only non-conflicting types from our types module
25pub use self::types::{
26    FrostCommitment, FrostGroupPublicKey, FrostKeyShare, FrostPublicKey, FrostSignature, GroupId,
27    HandshakeParameters, ParticipantId, PeerId, QuantumPeerIdentity, SecureSession, SessionId,
28    SessionState,
29};
30
31// Re-export all ant-quic PQC functions for convenience
32pub use self::ant_quic_integration::{
33    // Configuration functions
34    create_default_pqc_config,
35    create_pqc_memory_pool,
36    create_pqc_only_config,
37    // ML-DSA functions
38    generate_ml_dsa_keypair,
39    // ML-KEM functions
40    generate_ml_kem_keypair,
41    ml_dsa_sign,
42    ml_dsa_verify,
43    ml_kem_decapsulate,
44    ml_kem_encapsulate,
45};
46
47use serde::{Deserialize, Serialize};
48use thiserror::Error;
49
50// Primary post-quantum cryptography types from saorsa-pqc 0.3.0
51pub use saorsa_pqc::{
52    // Symmetric encryption (quantum-resistant)
53    ChaCha20Poly1305Cipher,
54    // Encrypted message types
55    EncryptedMessage,
56    // Algorithm implementations
57    MlDsa65,
58    MlDsaOperations,
59    MlKem768,
60    // Core traits for operations
61    MlKemOperations,
62    SymmetricEncryptedMessage,
63    // Errors
64    SymmetricError,
65    SymmetricKey,
66    // Library initialization
67    init as saorsa_pqc_init,
68    // Types and results
69    pqc::types::{
70        MlDsaPublicKey, MlDsaSecretKey, MlDsaSignature, MlKemCiphertext, MlKemPublicKey,
71        MlKemSecretKey, PqcError, PqcResult as SaorsaPqcResult, SharedSecret,
72    },
73};
74
75/// Quantum cryptography errors
76#[derive(Debug, Error)]
77pub enum QuantumCryptoError {
78    #[error("ML-KEM error: {0}")]
79    MlKemError(String),
80
81    #[error("ML-DSA error: {0}")]
82    MlDsaError(String),
83
84    #[error("Key generation failed: {0}")]
85    KeyGenerationError(String),
86
87    #[error("Invalid key material: {0}")]
88    InvalidKeyError(String),
89
90    #[error("Signature verification failed")]
91    SignatureVerificationFailed,
92
93    #[error("Encapsulation failed: {0}")]
94    EncapsulationError(String),
95
96    #[error("Decapsulation failed: {0}")]
97    DecapsulationError(String),
98
99    #[error("Unsupported algorithm: {0}")]
100    UnsupportedAlgorithm(String),
101}
102
103/// Result type for quantum crypto operations
104pub type Result<T> = std::result::Result<T, QuantumCryptoError>;
105
106/// Cryptographic algorithm capabilities
107#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
108pub struct CryptoCapabilities {
109    pub supports_ml_kem: bool,
110    pub supports_ml_dsa: bool,
111    pub supports_frost: bool,
112    pub threshold_capable: bool,
113    pub supported_versions: Vec<ProtocolVersion>,
114}
115
116impl Default for CryptoCapabilities {
117    fn default() -> Self {
118        Self {
119            supports_ml_kem: true,
120            supports_ml_dsa: true,
121            supports_frost: true,
122            threshold_capable: true,
123            supported_versions: vec![ProtocolVersion::V1, ProtocolVersion::V2],
124        }
125    }
126}
127
128/// Protocol version for algorithm negotiation
129#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
130pub enum ProtocolVersion {
131    /// Initial version with ML-KEM-768 and ML-DSA-65
132    V1,
133    /// Enhanced version with additional algorithms
134    V2,
135}
136
137/// Algorithm negotiation for establishing connections
138pub fn negotiate_algorithms(
139    local_caps: &CryptoCapabilities,
140    remote_caps: &CryptoCapabilities,
141) -> Result<NegotiatedAlgorithms> {
142    // Find common supported algorithms
143    let use_ml_kem = local_caps.supports_ml_kem && remote_caps.supports_ml_kem;
144    let use_ml_dsa = local_caps.supports_ml_dsa && remote_caps.supports_ml_dsa;
145
146    // Find common protocol version
147    let version = local_caps
148        .supported_versions
149        .iter()
150        .find(|v| remote_caps.supported_versions.contains(v))
151        .copied()
152        .ok_or_else(|| {
153            QuantumCryptoError::UnsupportedAlgorithm("No common protocol version".to_string())
154        })?;
155
156    // Select algorithms based on negotiated capabilities
157    let kem_algorithm = if use_ml_kem {
158        KemAlgorithm::MlKem768
159    } else {
160        return Err(QuantumCryptoError::UnsupportedAlgorithm(
161            "No common KEM algorithm".to_string(),
162        ));
163    };
164
165    let signature_algorithm = if use_ml_dsa {
166        SignatureAlgorithm::MlDsa65
167    } else {
168        return Err(QuantumCryptoError::UnsupportedAlgorithm(
169            "No common signature algorithm".to_string(),
170        ));
171    };
172
173    Ok(NegotiatedAlgorithms {
174        kem_algorithm,
175        signature_algorithm,
176        protocol_version: version,
177    })
178}
179
180/// Negotiated algorithm set
181#[derive(Debug, Clone, Serialize, Deserialize)]
182pub struct NegotiatedAlgorithms {
183    pub kem_algorithm: KemAlgorithm,
184    pub signature_algorithm: SignatureAlgorithm,
185    pub protocol_version: ProtocolVersion,
186}
187
188/// Key encapsulation mechanism algorithm
189#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
190pub enum KemAlgorithm {
191    MlKem768,
192}
193
194/// Signature algorithm
195#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
196pub enum SignatureAlgorithm {
197    MlDsa65,
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203
204    #[test]
205    fn test_saorsa_pqc_availability() {
206        // Test that saorsa-pqc types are available and can be instantiated
207        let _ml_kem = MlKem768;
208        let _ml_dsa = MlDsa65;
209
210        println!("✅ saorsa-pqc 0.3.0 types are available");
211        println!("✅ Confirmed we are using saorsa-pqc effectively");
212        println!("✅ ChaCha20Poly1305 integration ready for use");
213    }
214
215    #[test]
216    fn test_algorithm_negotiation() {
217        let local_caps = CryptoCapabilities::default();
218        let remote_caps = CryptoCapabilities {
219            supports_ml_kem: true,
220            supports_ml_dsa: true,
221            supports_frost: false,
222            threshold_capable: false,
223            supported_versions: vec![ProtocolVersion::V1],
224        };
225
226        let negotiated = negotiate_algorithms(&local_caps, &remote_caps).unwrap();
227        assert_eq!(negotiated.kem_algorithm, KemAlgorithm::MlKem768);
228        assert_eq!(negotiated.signature_algorithm, SignatureAlgorithm::MlDsa65);
229    }
230}