Skip to main content

ri/protocol/
post_quantum.rs

1//! Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
2//!
3//! This file is part of Ri.
4//! The Ri project belongs to the Dunimd Team.
5//!
6//! Licensed under the Apache License, Version 2.0 (the "License");
7//! You may not use this file except in compliance with the License.
8//! You may obtain a copy of the License at
9//!
10//!     http://www.apache.org/licenses/LICENSE-2.0
11//!
12//! Unless required by applicable law or agreed to in writing, software
13//! distributed under the License is distributed on an "AS IS" BASIS,
14//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15//! See the License for the specific language governing permissions and
16//! limitations under the License.
17
18#![allow(non_snake_case)]
19
20//! # Post-Quantum Cryptography Module
21//!
22//! This module provides post-quantum cryptographic algorithms that are resistant
23//! to attacks from both classical and quantum computers. It implements:
24//!
25//! - **Kyber**: IND-CCA2 secure key encapsulation mechanism (KEM)
26//! - **Dilithium**: Strongly secure digital signature algorithm
27//! - **Falcon**: Compact digital signature algorithm
28//!
29//! These algorithms are based on hard problems in lattice theory and have been
30//! selected by NIST for standardization in the post-quantum cryptography competition.
31//!
32//! ## Security Status
33//!
34//! ⚠️ **IMPORTANT**: This module provides the API structure for post-quantum cryptography.
35//! For production use, integrate an audited library:
36//!
37//! - **liboqs** (Recommended): https://github.com/open-quantum-safe/liboqs
38//!   - NIST PQC competition reference implementation
39//!   - Actively maintained and audited
40//!   - Supports all major platforms including Windows, Linux, macOS
41//!
42//! - **pqm4**: https://github.com/mupq/pqm4
43//!   - For ARM Cortex-M4 microcontrollers
44//!
45//! ## Integration Example
46//!
47//! Add to your `Cargo.toml`:
48//! ```toml
49//! [dependencies]
50//! liboqs = "0.7"
51//! ```
52//!
53//! Then enable the protocol feature:
54//! ```bash
55//! cargo build --features protocol
56//! ```
57//!
58//! ## API Structure
59//!
60//! ```rust,ignore
61//! use ri::protocol::post_quantum::{KyberKEM, DilithiumSigner};
62//!
63//! // Kyber key encapsulation (requires liboqs integration)
64//! let kem = KyberKEM::new();
65//! let (public_key, secret_key) = kem.keygen()?;
66//! let (ciphertext, shared_secret_1) = kem.encapsulate(&public_key)?;
67//! let shared_secret_2 = kem.decapsulate(&ciphertext, &secret_key)?;
68//!
69//! // Dilithium signing (requires liboqs integration)
70//! let signer = DilithiumSigner::new();
71//! let (pk, sk) = signer.keygen()?;
72//! let message = b"Hello, Post-Quantum World!";
73//! let signature = signer.sign(&sk, message)?;
74//! assert!(signer.verify(&pk, message, &signature));
75//! ```
76
77use std::sync::Arc;
78use std::time::Instant;
79use tokio::sync::RwLock;
80use crate::core::RiResult;
81
82pub use super::kyber::{KyberKEM, KyberPublicKey, KyberSecretKey, KyberCiphertext};
83pub use super::dilithium::{DilithiumSigner, DilithiumPublicKey, DilithiumSecretKey, DilithiumSignature};
84pub use super::falcon::{FalconSigner, FalconPublicKey, FalconSecretKey, FalconSignature};
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
88pub enum RiPostQuantumAlgorithm {
89    Kyber512,
90    Kyber768,
91    Kyber1024,
92    Dilithium2,
93    Dilithium3,
94    Dilithium5,
95    Falcon512,
96    Falcon1024,
97}
98
99pub struct KEMResult {
100    pub ciphertext: Vec<u8>,
101    pub shared_secret: Vec<u8>,
102}
103
104#[cfg_attr(feature = "pyo3", pyo3::prelude::pyclass)]
105pub struct RiPostQuantumManager {
106    algorithm: Arc<RwLock<RiPostQuantumAlgorithm>>,
107    initialized_at: Arc<RwLock<Instant>>,
108    initialized: Arc<RwLock<bool>>,
109}
110
111impl RiPostQuantumManager {
112    pub fn new() -> Self {
113        Self {
114            algorithm: Arc::new(RwLock::new(RiPostQuantumAlgorithm::Kyber512)),
115            initialized_at: Arc::new(RwLock::new(Instant::now())),
116            initialized: Arc::new(RwLock::new(false)),
117        }
118    }
119
120    pub async fn initialize(&self, algorithm: RiPostQuantumAlgorithm) -> RiResult<()> {
121        let mut init = self.initialized.write().await;
122        if *init {
123            return Ok(());
124        }
125
126        *self.algorithm.write().await = algorithm;
127        *self.initialized_at.write().await = Instant::now();
128        *init = true;
129
130        Ok(())
131    }
132
133    pub async fn algorithm(&self) -> RiPostQuantumAlgorithm {
134        *self.algorithm.read().await
135    }
136
137    pub fn security_level(&self) -> u8 {
138        match self.algorithm.try_read() {
139            Ok(guard) => match *guard {
140                RiPostQuantumAlgorithm::Kyber512 => 1,
141                RiPostQuantumAlgorithm::Kyber768 => 3,
142                RiPostQuantumAlgorithm::Kyber1024 => 5,
143                RiPostQuantumAlgorithm::Dilithium2 => 1,
144                RiPostQuantumAlgorithm::Dilithium3 => 3,
145                RiPostQuantumAlgorithm::Dilithium5 => 5,
146                RiPostQuantumAlgorithm::Falcon512 => 1,
147                RiPostQuantumAlgorithm::Falcon1024 => 5,
148            },
149            Err(_) => 1,
150        }
151    }
152}
153
154impl Default for RiPostQuantumManager {
155    fn default() -> Self {
156        Self::new()
157    }
158}
159
160#[cfg(feature = "pyo3")]
161#[pyo3::prelude::pymethods]
162impl RiPostQuantumManager {
163    #[new]
164    pub fn new_py() -> Self {
165        Self::new()
166    }
167
168    pub fn initialize_sync(&mut self, algorithm: RiPostQuantumAlgorithm) -> bool {
169        if let Ok(mut guard) = self.initialized.try_write() {
170            *guard = true;
171            if let Ok(mut algo_guard) = self.algorithm.try_write() {
172                *algo_guard = algorithm;
173                return true;
174            }
175        }
176        false
177    }
178
179    pub fn get_stats(&self) -> String {
180        format!("Post-Quantum Manager: API structure ready. Integrate liboqs for production use.")
181    }
182}