Skip to main content

quantaegis_sdk/
agility.rs

1//! Crypto-agile self-describing key containers supporting seamless algorithm migration.
2
3use core::fmt;
4
5use quantaegis_core::{Error, Kem, Result, SharedSecret, Zeroize};
6use quantaegis_hybrid::{XWing, xwing};
7use quantaegis_ml_kem::{MlKem512, MlKem768, MlKem1024, ml_kem_512, ml_kem_768, ml_kem_1024};
8
9use crate::OsRng;
10use crate::algorithm::KemAlgorithm;
11use crate::policy::SecurityPolicy;
12
13const PUBLIC_WIRE_MAGIC: &[u8; 4] = b"QAPK";
14const SECRET_WIRE_MAGIC: &[u8; 4] = b"QASK";
15const WIRE_VERSION: u8 = 0x01;
16
17/// Self-describing, validated crypto-agile public encapsulation key.
18#[derive(Clone, Eq, PartialEq)]
19pub struct AgilePublicKey {
20    algorithm: KemAlgorithm,
21    inner: PublicInner,
22}
23
24#[derive(Clone, Eq, PartialEq)]
25enum PublicInner {
26    MlKem512(Box<ml_kem_512::EncapsulationKey>),
27    MlKem768(Box<ml_kem_768::EncapsulationKey>),
28    MlKem1024(Box<ml_kem_1024::EncapsulationKey>),
29    XWing(Box<xwing::EncapsulationKey>),
30}
31
32impl AgilePublicKey {
33    /// Returns the KEM algorithm associated with this key.
34    #[inline]
35    pub const fn algorithm(&self) -> KemAlgorithm {
36        self.algorithm
37    }
38
39    /// Returns the raw algorithm-specific encapsulation key bytes.
40    pub fn raw_bytes(&self) -> &[u8] {
41        match &self.inner {
42            PublicInner::MlKem512(ek) => ek.as_bytes(),
43            PublicInner::MlKem768(ek) => ek.as_bytes(),
44            PublicInner::MlKem1024(ek) => ek.as_bytes(),
45            PublicInner::XWing(ek) => ek.as_bytes(),
46        }
47    }
48
49    /// Imports raw key bytes for an explicit `algorithm` and enforces `policy` + spec validation.
50    pub fn from_raw(policy: SecurityPolicy, algorithm: KemAlgorithm, bytes: &[u8]) -> Result<Self> {
51        policy.validate_kem(algorithm)?;
52        let inner = match algorithm {
53            KemAlgorithm::MlKem512 => {
54                PublicInner::MlKem512(Box::new(ml_kem_512::EncapsulationKey::from_bytes(bytes)?))
55            }
56            KemAlgorithm::MlKem768 => {
57                PublicInner::MlKem768(Box::new(ml_kem_768::EncapsulationKey::from_bytes(bytes)?))
58            }
59            KemAlgorithm::MlKem1024 => {
60                PublicInner::MlKem1024(Box::new(ml_kem_1024::EncapsulationKey::from_bytes(bytes)?))
61            }
62            KemAlgorithm::XWing => {
63                PublicInner::XWing(Box::new(xwing::EncapsulationKey::from_bytes(bytes)?))
64            }
65        };
66        Ok(Self { algorithm, inner })
67    }
68
69    /// Serializes this public key into a self-describing versioned binary format:
70    /// `QAPK || 0x01 || alg_id(u16 BE) || raw_key_bytes`.
71    pub fn to_wire_bytes(&self) -> Vec<u8> {
72        let raw = self.raw_bytes();
73        let mut out = Vec::with_capacity(7 + raw.len());
74        out.extend_from_slice(PUBLIC_WIRE_MAGIC);
75        out.push(WIRE_VERSION);
76        out.extend_from_slice(&self.algorithm.wire_id().to_be_bytes());
77        out.extend_from_slice(raw);
78        out
79    }
80
81    /// Deserializes a self-describing public key and enforces `policy` + spec key checks.
82    pub fn from_wire_bytes(policy: SecurityPolicy, bytes: &[u8]) -> Result<Self> {
83        if bytes.len() < 7 || &bytes[0..4] != PUBLIC_WIRE_MAGIC || bytes[4] != WIRE_VERSION {
84            return Err(Error::InvalidEncapsulationKey);
85        }
86        let alg_id = u16::from_be_bytes([bytes[5], bytes[6]]);
87        let alg = KemAlgorithm::from_wire_id(alg_id).map_err(|_| Error::InvalidEncapsulationKey)?;
88        Self::from_raw(policy, alg, &bytes[7..])
89    }
90
91    /// Encapsulates a fresh `(kem_ciphertext, shared_secret)` using the OS CSPRNG.
92    pub fn encaps(&self, policy: SecurityPolicy) -> Result<(Vec<u8>, SharedSecret)> {
93        policy.validate_kem(self.algorithm)?;
94        let mut rng = OsRng;
95        match &self.inner {
96            PublicInner::MlKem512(ek) => {
97                let (ct, ss) = MlKem512::encaps(ek, &mut rng)?;
98                Ok((ct.as_bytes().to_vec(), ss))
99            }
100            PublicInner::MlKem768(ek) => {
101                let (ct, ss) = MlKem768::encaps(ek, &mut rng)?;
102                Ok((ct.as_bytes().to_vec(), ss))
103            }
104            PublicInner::MlKem1024(ek) => {
105                let (ct, ss) = MlKem1024::encaps(ek, &mut rng)?;
106                Ok((ct.as_bytes().to_vec(), ss))
107            }
108            PublicInner::XWing(ek) => {
109                let (ct, ss) = XWing::encaps(ek, &mut rng)?;
110                Ok((ct.as_bytes().to_vec(), ss))
111            }
112        }
113    }
114}
115
116impl fmt::Debug for AgilePublicKey {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        write!(
119            f,
120            "AgilePublicKey({}, {} bytes)",
121            self.algorithm.name(),
122            self.raw_bytes().len()
123        )
124    }
125}
126
127/// Self-describing crypto-agile secret decapsulation key (automatically zeroized on drop).
128pub struct AgileSecretKey {
129    algorithm: KemAlgorithm,
130    inner: SecretInner,
131}
132
133enum SecretInner {
134    MlKem512(Box<ml_kem_512::DecapsulationKey>),
135    MlKem768(Box<ml_kem_768::DecapsulationKey>),
136    MlKem1024(Box<ml_kem_1024::DecapsulationKey>),
137    XWing(xwing::DecapsulationKey),
138}
139
140impl AgileSecretKey {
141    /// Returns the KEM algorithm associated with this secret key.
142    #[inline]
143    pub const fn algorithm(&self) -> KemAlgorithm {
144        self.algorithm
145    }
146
147    /// Explicitly borrows the raw algorithm-specific secret key bytes.
148    pub fn expose_raw_bytes(&self) -> &[u8] {
149        match &self.inner {
150            SecretInner::MlKem512(dk) => dk.expose_bytes(),
151            SecretInner::MlKem768(dk) => dk.expose_bytes(),
152            SecretInner::MlKem1024(dk) => dk.expose_bytes(),
153            SecretInner::XWing(dk) => dk.expose_bytes(),
154        }
155    }
156
157    /// Imports raw secret key bytes for an explicit `algorithm`, validating policy and FIPS 203 ยง7.3.
158    pub fn from_raw(policy: SecurityPolicy, algorithm: KemAlgorithm, bytes: &[u8]) -> Result<Self> {
159        policy.validate_kem(algorithm)?;
160        let inner = match algorithm {
161            KemAlgorithm::MlKem512 => {
162                SecretInner::MlKem512(Box::new(ml_kem_512::DecapsulationKey::from_bytes(bytes)?))
163            }
164            KemAlgorithm::MlKem768 => {
165                SecretInner::MlKem768(Box::new(ml_kem_768::DecapsulationKey::from_bytes(bytes)?))
166            }
167            KemAlgorithm::MlKem1024 => {
168                SecretInner::MlKem1024(Box::new(ml_kem_1024::DecapsulationKey::from_bytes(bytes)?))
169            }
170            KemAlgorithm::XWing => SecretInner::XWing(xwing::DecapsulationKey::from_bytes(bytes)?),
171        };
172        Ok(Self { algorithm, inner })
173    }
174
175    /// Serializes this secret key into a self-describing versioned binary format:
176    /// `QASK || 0x01 || alg_id(u16 BE) || raw_secret_bytes`.
177    ///
178    /// Callers MUST zeroize the returned `Vec<u8>` after writing it to secure storage.
179    pub fn expose_wire_bytes(&self) -> Vec<u8> {
180        let raw = self.expose_raw_bytes();
181        let mut out = Vec::with_capacity(7 + raw.len());
182        out.extend_from_slice(SECRET_WIRE_MAGIC);
183        out.push(WIRE_VERSION);
184        out.extend_from_slice(&self.algorithm.wire_id().to_be_bytes());
185        out.extend_from_slice(raw);
186        out
187    }
188
189    /// Reads the KEM algorithm declared by a self-describing secret key wire frame **without**
190    /// enforcing any policy or validating the key material.
191    ///
192    /// Intended for keyring routing: callers holding serialized keys can select the candidates
193    /// whose algorithm matches an envelope (see [`crate::Envelope::inspect`]) and parse only those
194    /// with [`AgileSecretKey::from_wire_bytes`] under the active policy, so that unrelated legacy
195    /// keys in the ring never trigger a policy violation.
196    ///
197    /// Returns [`Error::InvalidDecapsulationKey`] if the wire header is malformed or declares an
198    /// unknown algorithm (the same checks performed by [`AgileSecretKey::from_wire_bytes`]).
199    pub fn wire_algorithm(bytes: &[u8]) -> Result<KemAlgorithm> {
200        if bytes.len() < 7 || &bytes[0..4] != SECRET_WIRE_MAGIC || bytes[4] != WIRE_VERSION {
201            return Err(Error::InvalidDecapsulationKey);
202        }
203        let alg_id = u16::from_be_bytes([bytes[5], bytes[6]]);
204        KemAlgorithm::from_wire_id(alg_id).map_err(|_| Error::InvalidDecapsulationKey)
205    }
206
207    /// Deserializes a self-describing secret key and enforces `policy` + spec key checks.
208    pub fn from_wire_bytes(policy: SecurityPolicy, bytes: &[u8]) -> Result<Self> {
209        let alg = Self::wire_algorithm(bytes)?;
210        Self::from_raw(policy, alg, &bytes[7..])
211    }
212
213    /// Decapsulates raw `kem_ct` bytes under `policy`.
214    pub fn decaps(&self, policy: SecurityPolicy, kem_ct: &[u8]) -> Result<SharedSecret> {
215        policy.validate_kem(self.algorithm)?;
216        match &self.inner {
217            SecretInner::MlKem512(dk) => {
218                let ct = ml_kem_512::Ciphertext::from_bytes(kem_ct)?;
219                MlKem512::decaps(dk, &ct)
220            }
221            SecretInner::MlKem768(dk) => {
222                let ct = ml_kem_768::Ciphertext::from_bytes(kem_ct)?;
223                MlKem768::decaps(dk, &ct)
224            }
225            SecretInner::MlKem1024(dk) => {
226                let ct = ml_kem_1024::Ciphertext::from_bytes(kem_ct)?;
227                MlKem1024::decaps(dk, &ct)
228            }
229            SecretInner::XWing(dk) => {
230                let ct = xwing::Ciphertext::from_bytes(kem_ct)?;
231                XWing::decaps(dk, &ct)
232            }
233        }
234    }
235}
236
237impl Zeroize for AgileSecretKey {
238    fn zeroize(&mut self) {
239        match &mut self.inner {
240            SecretInner::MlKem512(dk) => dk.zeroize(),
241            SecretInner::MlKem768(dk) => dk.zeroize(),
242            SecretInner::MlKem1024(dk) => dk.zeroize(),
243            SecretInner::XWing(dk) => dk.zeroize(),
244        }
245    }
246}
247
248impl fmt::Debug for AgileSecretKey {
249    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        write!(
251            f,
252            "AgileSecretKey({}, [REDACTED; {} bytes])",
253            self.algorithm.name(),
254            self.expose_raw_bytes().len()
255        )
256    }
257}
258
259/// Generated crypto-agile `(AgilePublicKey, AgileSecretKey)` pair.
260pub struct AgileKeyPair {
261    /// Public encapsulation key.
262    pub public: AgilePublicKey,
263    /// Private decapsulation key (zeroized on drop).
264    pub secret: AgileSecretKey,
265}
266
267impl AgileKeyPair {
268    /// Generates a fresh key pair for `algorithm` under `policy` using the OS CSPRNG.
269    pub fn generate(policy: SecurityPolicy, algorithm: KemAlgorithm) -> Result<Self> {
270        policy.validate_kem(algorithm)?;
271        let mut rng = OsRng;
272        let (pub_inner, sec_inner) = match algorithm {
273            KemAlgorithm::MlKem512 => {
274                let (ek, dk) = MlKem512::keygen(&mut rng)?;
275                (
276                    PublicInner::MlKem512(Box::new(ek)),
277                    SecretInner::MlKem512(Box::new(dk)),
278                )
279            }
280            KemAlgorithm::MlKem768 => {
281                let (ek, dk) = MlKem768::keygen(&mut rng)?;
282                (
283                    PublicInner::MlKem768(Box::new(ek)),
284                    SecretInner::MlKem768(Box::new(dk)),
285                )
286            }
287            KemAlgorithm::MlKem1024 => {
288                let (ek, dk) = MlKem1024::keygen(&mut rng)?;
289                (
290                    PublicInner::MlKem1024(Box::new(ek)),
291                    SecretInner::MlKem1024(Box::new(dk)),
292                )
293            }
294            KemAlgorithm::XWing => {
295                let (ek, dk) = XWing::keygen(&mut rng)?;
296                (PublicInner::XWing(Box::new(ek)), SecretInner::XWing(dk))
297            }
298        };
299
300        Ok(Self {
301            public: AgilePublicKey {
302                algorithm,
303                inner: pub_inner,
304            },
305            secret: AgileSecretKey {
306                algorithm,
307                inner: sec_inner,
308            },
309        })
310    }
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    #[test]
318    fn secret_wire_algorithm_reads_header_without_policy_check() {
319        let kp = AgileKeyPair::generate(SecurityPolicy::Permissive, KemAlgorithm::MlKem768)
320            .ok()
321            .unwrap_or_else(|| unreachable!());
322        let mut wire = kp.secret.expose_wire_bytes();
323
324        // ML-KEM-768 violates HybridRequired, but routing only reads the declared algorithm.
325        assert_eq!(
326            AgileSecretKey::wire_algorithm(&wire),
327            Ok(KemAlgorithm::MlKem768)
328        );
329        assert_eq!(
330            AgileSecretKey::from_wire_bytes(SecurityPolicy::HybridRequired, &wire).err(),
331            Some(Error::PolicyViolation)
332        );
333
334        // Malformed headers are still rejected.
335        assert_eq!(
336            AgileSecretKey::wire_algorithm(&wire[..6]),
337            Err(Error::InvalidDecapsulationKey)
338        );
339        let mut bad_magic = wire.clone();
340        bad_magic[0] ^= 0xFF;
341        assert_eq!(
342            AgileSecretKey::wire_algorithm(&bad_magic),
343            Err(Error::InvalidDecapsulationKey)
344        );
345        let mut bad_alg = wire.clone();
346        bad_alg[5] = 0xFF;
347        assert_eq!(
348            AgileSecretKey::wire_algorithm(&bad_alg),
349            Err(Error::InvalidDecapsulationKey)
350        );
351
352        bad_magic.zeroize();
353        bad_alg.zeroize();
354        wire.zeroize();
355    }
356}