Skip to main content

qualia_core_db/crypto/network/
share_encoding.rs

1//! CRY-02.03 **PARTIAL** — freeze responder-share wire encoding and ML-KEM-then-X25519 IKM.
2//!
3//! Draft until FND-03 freeze: responder share wire bytes are exactly
4//! `ml_kem_ct || x25519_pk` with **no version prefix**. Initiator share encoding
5//! lives in `pq_handshake`; this module owns the responder half and the hybrid
6//! IKM concat used as HKDF input.
7//!
8//! CRY-02.12 remainder: a **live** ML-KEM-768 encapsulate/decapsulate round-trip
9//! is exercised in tests. That ciphertext is **not a frozen hex vector** —
10//! `encapsulate` draws OS RNG, so ct bytes change every run. Do not treat live
11//! KEM ciphertext as a conformance fixture. Dual proofs, record vectors, and
12//! length-delimited transcripts remain open. No security proof is claimed.
13//!
14//! Crypto stays below `net::qdnf`: this module uses raw arrays only.
15
16use super::errors::CryptoError;
17use super::types::{ML_KEM_768_CT_LEN, ML_KEM_SS_LEN, X25519_LEN};
18
19/// Exact responder-share slice length: `ML_KEM_768_CT_LEN || X25519_LEN`.
20pub const RESPONDER_SHARE_WIRE_LEN: usize = ML_KEM_768_CT_LEN + X25519_LEN;
21
22const _: () = assert!(ML_KEM_SS_LEN + X25519_LEN == 64);
23const _: () = assert!(RESPONDER_SHARE_WIRE_LEN == 1088 + 32);
24
25/// Encode responder share as `ml_kem_ct || x25519_pk` (draft; no version byte).
26///
27/// Writes exactly [`RESPONDER_SHARE_WIRE_LEN`] bytes. [`CryptoError::Capacity`]
28/// if `out` is shorter than that.
29pub fn encode_responder_share(
30    ml_kem_ct: &[u8; ML_KEM_768_CT_LEN],
31    x25519_pk: &[u8; X25519_LEN],
32    out: &mut [u8],
33) -> Result<usize, CryptoError> {
34    if out.len() < RESPONDER_SHARE_WIRE_LEN {
35        return Err(CryptoError::Capacity);
36    }
37    out[..ML_KEM_768_CT_LEN].copy_from_slice(ml_kem_ct);
38    out[ML_KEM_768_CT_LEN..RESPONDER_SHARE_WIRE_LEN].copy_from_slice(x25519_pk);
39    Ok(RESPONDER_SHARE_WIRE_LEN)
40}
41
42/// Decode responder share from `ml_kem_ct || x25519_pk`.
43///
44/// [`CryptoError::Truncated`] if `src.len() < RESPONDER_SHARE_WIRE_LEN`.
45/// Extra bytes are [`CryptoError::Malformed`]. Exact length only.
46pub fn decode_responder_share(
47    src: &[u8],
48) -> Result<([u8; ML_KEM_768_CT_LEN], [u8; X25519_LEN]), CryptoError> {
49    if src.len() < RESPONDER_SHARE_WIRE_LEN {
50        return Err(CryptoError::Truncated);
51    }
52    if src.len() != RESPONDER_SHARE_WIRE_LEN {
53        return Err(CryptoError::Malformed);
54    }
55    let mut ct = [0u8; ML_KEM_768_CT_LEN];
56    let mut pk = [0u8; X25519_LEN];
57    ct.copy_from_slice(&src[..ML_KEM_768_CT_LEN]);
58    pk.copy_from_slice(&src[ML_KEM_768_CT_LEN..]);
59    Ok((ct, pk))
60}
61
62/// Concatenate ML-KEM shared secret then X25519 shared secret (HKDF IKM order).
63pub fn hybrid_ikm(
64    ml_kem_ss: &[u8; ML_KEM_SS_LEN],
65    x25519_ss: &[u8; X25519_LEN],
66    out: &mut [u8; 64],
67) {
68    out[..ML_KEM_SS_LEN].copy_from_slice(ml_kem_ss);
69    out[ML_KEM_SS_LEN..].copy_from_slice(x25519_ss);
70}
71
72/// Draft encoding has no version prefix on responder-share wire bytes.
73pub fn responder_share_has_version_prefix() -> bool {
74    false
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::crypto::network::kem::{encapsulate, MlKem768Secret};
81
82    fn patterned_ct() -> [u8; ML_KEM_768_CT_LEN] {
83        let mut ct = [0u8; ML_KEM_768_CT_LEN];
84        let mut i = 0usize;
85        while i < ML_KEM_768_CT_LEN {
86            ct[i] = (i as u8).wrapping_add(0xA5);
87            i += 1;
88        }
89        ct[0] = 0xC1;
90        ct[ML_KEM_768_CT_LEN - 1] = 0xC2;
91        ct
92    }
93
94    fn patterned_x25519_pk() -> [u8; X25519_LEN] {
95        let mut pk = [0u8; X25519_LEN];
96        let mut i = 0usize;
97        while i < X25519_LEN {
98            pk[i] = (i as u8).wrapping_add(0x5A);
99            i += 1;
100        }
101        pk[0] = 0x11;
102        pk[X25519_LEN - 1] = 0xEE;
103        pk
104    }
105
106    #[test]
107    fn encode_decode_patterned_round_trip() {
108        let ct = patterned_ct();
109        let pk = patterned_x25519_pk();
110        let mut wire = [0u8; RESPONDER_SHARE_WIRE_LEN];
111        let n = encode_responder_share(&ct, &pk, &mut wire).unwrap();
112        assert_eq!(n, RESPONDER_SHARE_WIRE_LEN);
113        assert_eq!(&wire[..ML_KEM_768_CT_LEN], &ct);
114        assert_eq!(&wire[ML_KEM_768_CT_LEN..], &pk);
115
116        let (decoded_ct, decoded_pk) = decode_responder_share(&wire).unwrap();
117        assert_eq!(decoded_ct, ct);
118        assert_eq!(decoded_pk, pk);
119    }
120
121    #[test]
122    fn truncated_malformed_and_capacity() {
123        let ct = patterned_ct();
124        let pk = patterned_x25519_pk();
125        let mut short = [0u8; 8];
126        assert_eq!(
127            encode_responder_share(&ct, &pk, &mut short),
128            Err(CryptoError::Capacity)
129        );
130
131        let mut wire = [0u8; RESPONDER_SHARE_WIRE_LEN];
132        encode_responder_share(&ct, &pk, &mut wire).unwrap();
133        match decode_responder_share(&wire[..RESPONDER_SHARE_WIRE_LEN - 1]) {
134            Err(e) => assert_eq!(e, CryptoError::Truncated),
135            Ok(_) => panic!("truncated responder share decoded"),
136        }
137        let mut extra = [0u8; RESPONDER_SHARE_WIRE_LEN + 1];
138        extra[..RESPONDER_SHARE_WIRE_LEN].copy_from_slice(&wire);
139        match decode_responder_share(&extra) {
140            Err(e) => assert_eq!(e, CryptoError::Malformed),
141            Ok(_) => panic!("oversize responder share decoded"),
142        }
143    }
144
145    #[test]
146    fn hybrid_ikm_kem_then_x25519() {
147        let mut kem = [0u8; ML_KEM_SS_LEN];
148        let mut x = [0u8; X25519_LEN];
149        kem[0] = 0xAA;
150        kem[ML_KEM_SS_LEN - 1] = 0xAB;
151        x[0] = 0x55;
152        x[X25519_LEN - 1] = 0x56;
153        let mut out = [0u8; 64];
154        hybrid_ikm(&kem, &x, &mut out);
155        assert_eq!(out[0], 0xAA);
156        assert_eq!(out[ML_KEM_SS_LEN - 1], 0xAB);
157        assert_eq!(out[ML_KEM_SS_LEN], 0x55);
158        assert_eq!(out[63], 0x56);
159        assert_eq!(&out[..ML_KEM_SS_LEN], &kem);
160        assert_eq!(&out[ML_KEM_SS_LEN..], &x);
161    }
162
163    #[test]
164    fn no_version_prefix() {
165        assert!(!responder_share_has_version_prefix());
166    }
167
168    /// Live encapsulate uses RNG. Ciphertext is not a frozen CRY-02.12 vector.
169    #[test]
170    fn live_ml_kem_encapsulate_then_encode_recovers_ct() {
171        let (sk, pk) = MlKem768Secret::generate().unwrap();
172        let (ss_enc, ct) = encapsulate(&pk).unwrap();
173        let ss_dec = sk.decapsulate(&ct).unwrap();
174        assert_eq!(ss_enc, ss_dec);
175
176        let dummy_x25519 = patterned_x25519_pk();
177        let mut wire = [0u8; RESPONDER_SHARE_WIRE_LEN];
178        let n = encode_responder_share(&ct, &dummy_x25519, &mut wire).unwrap();
179        assert_eq!(n, RESPONDER_SHARE_WIRE_LEN);
180
181        let (decoded_ct, decoded_pk) = decode_responder_share(&wire).unwrap();
182        assert_eq!(decoded_ct, ct);
183        assert_eq!(decoded_pk, dummy_x25519);
184        // Live ct is RNG-dependent: patterned fixture must not match this run.
185        assert_ne!(decoded_ct, patterned_ct());
186    }
187}