Skip to main content

vector_core/transfer/
crypto.rs

1//! The transfer's cryptography: SPAKE2 over the code, the commitment that stops either side picking
2//! its message after seeing the other's, the transcript every key is bound to, the sealed messages
3//! that follow, and the ML-KEM-1024 exchange whose secret joins SPAKE2's before the identity is
4//! sealed, so a recording is safe from a future quantum computer too.
5
6use hkdf::Hkdf;
7use libcrux_ml_kem::mlkem1024;
8use nostr_sdk::prelude::{Keys, PublicKey, SecretKey};
9use rand::RngCore;
10use sha2::{Digest, Sha256};
11use spake2::{Ed25519Group, Identity, Password, Spake2};
12use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
13
14use super::code::Code;
15use crate::crypto::chachapoly::ChaCha20Poly1305;
16
17const PROTOCOL: &[u8] = b"vector-transfer-v1";
18/// A SPAKE2 message: the symmetric side byte and a compressed Edwards point.
19pub const PAKE_MSG_LEN: usize = 33;
20/// Digits in the number the user carries from the new device to the old one.
21pub const SAS_DIGITS: usize = 6;
22
23/// One side's SPAKE2 run over the code.
24pub struct Pake {
25    state: Spake2<Ed25519Group>,
26    msg: Vec<u8>,
27}
28
29impl Pake {
30    pub fn start(code: &Code) -> Self {
31        let password = code.canonical();
32        let (state, msg) = Spake2::<Ed25519Group>::start_symmetric(&Password::new(password.as_bytes()), &Identity::new(PROTOCOL));
33        Self { state, msg }
34    }
35
36    pub fn msg(&self) -> &[u8] {
37        &self.msg
38    }
39
40    /// The shared secret. Refuses our own message reflected back and a point of small order, the
41    /// two checks spake2 leaves to its caller.
42    pub fn finish(self, peer: &[u8]) -> Result<Zeroizing<Vec<u8>>, &'static str> {
43        if peer.len() != PAKE_MSG_LEN {
44            return Err("malformed pake message");
45        }
46        if peer == self.msg.as_slice() {
47            return Err("reflected pake message");
48        }
49        let point: [u8; 32] = peer[1..].try_into().map_err(|_| "malformed pake message")?;
50        match curve25519_dalek::edwards::CompressedEdwardsY(point).decompress() {
51            Some(p) if !p.is_small_order() => {}
52            _ => return Err("invalid pake point"),
53        }
54        self.state.finish(peer).map(Zeroizing::new).map_err(|_| "pake failed")
55    }
56}
57
58/// What the joiner publishes before it sees the shower's message, so it can't choose its own later.
59pub fn commitment(msg: &[u8]) -> [u8; 32] {
60    let mut h = Sha256::new();
61    h.update(PROTOCOL);
62    h.update(b"/commit");
63    h.update(msg);
64    h.finalize().into()
65}
66
67/// The meeting room for a nameplate. Derived from the nameplate alone and public by design: a room
68/// derived from the words would let anyone watching the relays search for the code offline.
69pub fn room(nameplate: u16) -> PublicKey {
70    let mut counter = 0u8;
71    loop {
72        let mut h = Sha256::new();
73        h.update(PROTOCOL);
74        h.update(b"/room");
75        h.update(nameplate.to_be_bytes());
76        h.update([counter]);
77        let digest: [u8; 32] = h.finalize().into();
78        if let Ok(secret) = SecretKey::from_slice(&digest) {
79            return Keys::new(secret).public_key();
80        }
81        counter += 1;
82    }
83}
84
85/// Everything both devices agreed on, in a fixed order with fixed lengths.
86pub fn transcript(room: &PublicKey, shower: &PublicKey, joiner: &PublicKey, msg_shower: &[u8], msg_joiner: &[u8]) -> [u8; 32] {
87    let mut h = Sha256::new();
88    h.update(PROTOCOL);
89    h.update(b"/transcript");
90    h.update(room.to_bytes());
91    h.update(shower.to_bytes());
92    h.update(joiner.to_bytes());
93    for msg in [msg_shower, msg_joiner] {
94        h.update((msg.len() as u16).to_be_bytes());
95        h.update(msg);
96    }
97    h.finalize().into()
98}
99
100/// Which way a sealed message travels; each direction has its own key.
101#[derive(Clone, Copy, PartialEq, Eq, Debug)]
102pub enum Dir {
103    ShowerToJoiner,
104    JoinerToShower,
105}
106
107/// The sealed message kinds. Each is sent at most once per direction, so the kind is the nonce.
108#[derive(Clone, Copy, PartialEq, Eq, Debug)]
109#[repr(u8)]
110pub enum Sealed {
111    Hello = 1,
112    Bundle = 2,
113    Deny = 3,
114    Ack = 4,
115}
116
117/// An ML-KEM-1024 encapsulation key's size.
118pub const KEM_PUBLIC_LEN: usize = 1568;
119/// An ML-KEM-1024 ciphertext's size.
120pub const KEM_CIPHERTEXT_LEN: usize = 1568;
121
122/// The receiver's ML-KEM-1024 key, held as its 64-byte FIPS 203 seed: the expanded private key is
123/// rebuilt only to decapsulate, then wiped.
124#[derive(Zeroize, ZeroizeOnDrop)]
125pub struct KemSeed([u8; 64]);
126
127impl KemSeed {
128    pub fn generate() -> Self {
129        let mut seed = [0u8; 64];
130        rand::rngs::OsRng.fill_bytes(&mut seed);
131        Self(seed)
132    }
133
134    fn expand(&self) -> (libcrux_ml_kem::MlKemPrivateKey<3168>, Vec<u8>) {
135        let (sk, pk) = mlkem1024::generate_key_pair(self.0).into_parts();
136        (sk, pk.as_slice().to_vec())
137    }
138
139    pub fn public_key(&self) -> Vec<u8> {
140        let (mut sk, pk) = self.expand();
141        sk[0..].zeroize();
142        pk
143    }
144
145    /// The shared secret in `ciphertext`. A tampered ciphertext yields an unrelated secret (ML-KEM's
146    /// implicit rejection), which the sealed bundle then refuses to open under.
147    pub fn decapsulate(&self, ciphertext: &[u8]) -> Result<Zeroizing<[u8; 32]>, ()> {
148        let ct = mlkem1024::MlKem1024Ciphertext::try_from(ciphertext).map_err(|_| ())?;
149        let (mut sk, _) = self.expand();
150        let shared = Zeroizing::new(mlkem1024::decapsulate(&sk, &ct));
151        sk[0..].zeroize();
152        Ok(shared)
153    }
154}
155
156/// Whether `public_key` is a well-formed ML-KEM-1024 encapsulation key (FIPS 203's check).
157pub fn kem_public_ok(public_key: &[u8]) -> bool {
158    mlkem1024::MlKem1024PublicKey::try_from(public_key).is_ok_and(|pk| mlkem1024::validate_public_key(&pk))
159}
160
161/// Encapsulate to the receiver's key, once it passes FIPS 203's encapsulation key check.
162pub fn kem_encapsulate(public_key: &[u8]) -> Result<(Vec<u8>, Zeroizing<[u8; 32]>), ()> {
163    let pk = mlkem1024::MlKem1024PublicKey::try_from(public_key).map_err(|_| ())?;
164    if !mlkem1024::validate_public_key(&pk) {
165        return Err(());
166    }
167    let mut randomness = Zeroizing::new([0u8; 32]);
168    rand::rngs::OsRng.fill_bytes(randomness.as_mut());
169    let (ct, shared) = mlkem1024::encapsulate(&pk, *randomness);
170    Ok((ct.as_slice().to_vec(), Zeroizing::new(shared)))
171}
172
173#[derive(Zeroize, ZeroizeOnDrop)]
174pub struct SessionKeys {
175    shower_to_joiner: [u8; 32],
176    joiner_to_shower: [u8; 32],
177    transcript: [u8; 32],
178    sas: [u8; SAS_DIGITS],
179    /// What the post-quantum secret is mixed with; never used to encrypt by itself.
180    chain: [u8; 32],
181}
182
183impl SessionKeys {
184    pub fn derive(shared: &[u8], transcript: [u8; 32]) -> Self {
185        let hk = Hkdf::<Sha256>::new(Some(&transcript), shared);
186        let mut keys = Self { shower_to_joiner: [0; 32], joiner_to_shower: [0; 32], transcript, sas: [0; SAS_DIGITS], chain: [0; 32] };
187        hk.expand(b"vector-transfer-v1/shower-to-joiner", &mut keys.shower_to_joiner).expect("32 bytes");
188        hk.expand(b"vector-transfer-v1/joiner-to-shower", &mut keys.joiner_to_shower).expect("32 bytes");
189        hk.expand(b"vector-transfer-v1/chain", &mut keys.chain).expect("32 bytes");
190        let mut sas = Zeroizing::new([0u8; 8]);
191        hk.expand(b"vector-transfer-v1/sas", sas.as_mut()).expect("8 bytes");
192        let mut n = u64::from_be_bytes(*sas) % 10u64.pow(SAS_DIGITS as u32);
193        for d in keys.sas.iter_mut().rev() {
194            *d = b'0' + (n % 10) as u8;
195            n /= 10;
196        }
197        keys
198    }
199
200    /// The keys the identity travels under: SPAKE2's secret and ML-KEM's together, bound to the
201    /// encapsulation key and ciphertext. Reading the bundle takes breaking both.
202    pub fn hybrid(&self, kem_public: &[u8], kem_ciphertext: &[u8], kem_shared: &[u8; 32]) -> Self {
203        let mut salt = Sha256::new();
204        salt.update(PROTOCOL);
205        salt.update(b"/hybrid");
206        salt.update(self.transcript);
207        for part in [kem_public, kem_ciphertext] {
208            salt.update((part.len() as u16).to_be_bytes());
209            salt.update(part);
210        }
211        let salt: [u8; 32] = salt.finalize().into();
212        let mut ikm = Zeroizing::new([0u8; 64]);
213        ikm[..32].copy_from_slice(&self.chain);
214        ikm[32..].copy_from_slice(kem_shared);
215        let hk = Hkdf::<Sha256>::new(Some(&salt), ikm.as_ref());
216        let mut keys = Self { shower_to_joiner: [0; 32], joiner_to_shower: [0; 32], transcript: salt, sas: self.sas, chain: [0; 32] };
217        hk.expand(b"vector-transfer-v1/hybrid/shower-to-joiner", &mut keys.shower_to_joiner).expect("32 bytes");
218        hk.expand(b"vector-transfer-v1/hybrid/joiner-to-shower", &mut keys.joiner_to_shower).expect("32 bytes");
219        keys
220    }
221
222    /// The number both screens agree on: shown on the receiver, typed on the sender.
223    pub fn sas(&self) -> String {
224        String::from_utf8_lossy(&self.sas).into_owned()
225    }
226
227    /// Whether `typed` is the number, compared in constant time. Only its digits count, so a
228    /// keypad's "123-456" or "123 456" reads the same.
229    pub fn sas_matches(&self, typed: &str) -> bool {
230        let digits: Vec<u8> = typed.bytes().filter(u8::is_ascii_digit).collect();
231        digits.len() == SAS_DIGITS && digits.iter().zip(self.sas.iter()).fold(0u8, |acc, (a, b)| acc | (a ^ b)) == 0
232    }
233
234    fn cipher(&self, dir: Dir) -> ChaCha20Poly1305 {
235        ChaCha20Poly1305::new(match dir {
236            Dir::ShowerToJoiner => &self.shower_to_joiner,
237            Dir::JoinerToShower => &self.joiner_to_shower,
238        })
239    }
240
241    fn nonce_and_aad(&self, kind: Sealed) -> ([u8; 12], [u8; 33]) {
242        let mut nonce = [0u8; 12];
243        nonce[0] = kind as u8;
244        let mut aad = [0u8; 33];
245        aad[..32].copy_from_slice(&self.transcript);
246        aad[32] = kind as u8;
247        (nonce, aad)
248    }
249
250    pub fn seal(&self, dir: Dir, kind: Sealed, plain: &[u8]) -> Vec<u8> {
251        let (nonce, aad) = self.nonce_and_aad(kind);
252        let mut buf = plain.to_vec();
253        let tag = self.cipher(dir).seal_in_place(&nonce, &aad, &mut buf).expect("transfer messages are small");
254        buf.extend_from_slice(&tag);
255        buf
256    }
257
258    pub fn open(&self, dir: Dir, kind: Sealed, sealed: &[u8]) -> Result<Zeroizing<Vec<u8>>, ()> {
259        if sealed.len() < 16 {
260            return Err(());
261        }
262        let (nonce, aad) = self.nonce_and_aad(kind);
263        let (body, tag) = sealed.split_at(sealed.len() - 16);
264        let tag: [u8; 16] = tag.try_into().map_err(|_| ())?;
265        let mut buf = Zeroizing::new(body.to_vec());
266        self.cipher(dir).open_in_place(&nonce, &aad, &mut buf, &tag).map_err(|_| ())?;
267        Ok(buf)
268    }
269}
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274
275    fn pair(code_a: &str, code_b: &str) -> (Result<Zeroizing<Vec<u8>>, &'static str>, Result<Zeroizing<Vec<u8>>, &'static str>) {
276        let a = Pake::start(&Code::parse(code_a).unwrap());
277        let b = Pake::start(&Code::parse(code_b).unwrap());
278        let (ma, mb) = (a.msg().to_vec(), b.msg().to_vec());
279        (a.finish(&mb), b.finish(&ma))
280    }
281
282    #[test]
283    fn the_same_code_agrees_and_a_different_one_does_not() {
284        let (a, b) = pair("7-orbit-lemon-stage", "7-orbit-lemon-stage");
285        assert_eq!(a.unwrap(), b.unwrap());
286        let (a, b) = pair("7-orbit-lemon-stage", "7-orbit-lemon-stamp");
287        assert_ne!(a.unwrap(), b.unwrap());
288    }
289
290    #[test]
291    fn a_reflected_or_degenerate_message_is_refused() {
292        let code = Code::parse("7-orbit-lemon-stage").unwrap();
293        let a = Pake::start(&code);
294        let own = a.msg().to_vec();
295        assert_eq!(a.finish(&own).unwrap_err(), "reflected pake message");
296        let mut identity = [0u8; PAKE_MSG_LEN];
297        identity[0] = 0x53;
298        identity[1] = 1;
299        assert_eq!(Pake::start(&code).finish(&identity).unwrap_err(), "invalid pake point");
300        assert!(Pake::start(&code).finish(&[0x53; 5]).is_err());
301    }
302
303    #[test]
304    fn sealed_messages_bind_direction_kind_and_transcript() {
305        let keys = SessionKeys::derive(b"shared", [1; 32]);
306        let sealed = keys.seal(Dir::JoinerToShower, Sealed::Hello, b"hi");
307        assert_eq!(&*keys.open(Dir::JoinerToShower, Sealed::Hello, &sealed).unwrap(), b"hi");
308        assert!(keys.open(Dir::ShowerToJoiner, Sealed::Hello, &sealed).is_err(), "reflected to the other direction");
309        assert!(keys.open(Dir::JoinerToShower, Sealed::Bundle, &sealed).is_err(), "relabelled as another kind");
310        let other = SessionKeys::derive(b"shared", [2; 32]);
311        assert!(other.open(Dir::JoinerToShower, Sealed::Hello, &sealed).is_err(), "spliced into another transcript");
312        let mut flipped = sealed.clone();
313        flipped[0] ^= 1;
314        assert!(keys.open(Dir::JoinerToShower, Sealed::Hello, &flipped).is_err());
315    }
316
317    #[test]
318    fn the_sas_is_six_digits_and_matches_only_itself() {
319        let keys = SessionKeys::derive(b"shared", [3; 32]);
320        let sas = keys.sas();
321        assert_eq!(sas.len(), SAS_DIGITS);
322        assert!(sas.bytes().all(|b| b.is_ascii_digit()));
323        assert!(keys.sas_matches(&sas));
324        assert!(keys.sas_matches(&format!("{} {}", &sas[..3], &sas[3..])));
325        for sep in ["-", ".", ",", "\u{2013}"] {
326            assert!(keys.sas_matches(&format!("{}{sep}{}", &sas[..3], &sas[3..])), "a keypad separator {sep:?}");
327        }
328        let mut wrong = sas.clone().into_bytes();
329        wrong[5] = if wrong[5] == b'9' { b'0' } else { wrong[5] + 1 };
330        assert!(!keys.sas_matches(std::str::from_utf8(&wrong).unwrap()));
331        assert!(!keys.sas_matches(&sas[..5]));
332    }
333
334    #[test]
335    fn the_kem_round_trips_and_a_tampered_ciphertext_opens_nothing() {
336        let seed = KemSeed::generate();
337        let pk = seed.public_key();
338        assert_eq!(pk.len(), KEM_PUBLIC_LEN);
339        let (ct, sent) = kem_encapsulate(&pk).unwrap();
340        assert_eq!(ct.len(), KEM_CIPHERTEXT_LEN);
341        assert_eq!(*seed.decapsulate(&ct).unwrap(), *sent);
342        let mut bent = ct.clone();
343        bent[0] ^= 1;
344        assert_ne!(*seed.decapsulate(&bent).unwrap(), *sent, "implicit rejection");
345        assert!(seed.decapsulate(&ct[1..]).is_err());
346        assert!(kem_encapsulate(&pk[1..]).is_err());
347        let mut out_of_range = pk.clone();
348        out_of_range[..2].copy_from_slice(&[0xff, 0xff]);
349        assert!(kem_encapsulate(&out_of_range).is_err(), "FIPS 203 encapsulation key check");
350    }
351
352    #[test]
353    fn the_hybrid_keys_need_both_secrets() {
354        let classical = SessionKeys::derive(b"shared", [4; 32]);
355        let seed = KemSeed::generate();
356        let pk = seed.public_key();
357        let (ct, ss) = kem_encapsulate(&pk).unwrap();
358        let hybrid = classical.hybrid(&pk, &ct, &ss);
359        let sealed = hybrid.seal(Dir::ShowerToJoiner, Sealed::Bundle, b"identity");
360        assert!(classical.open(Dir::ShowerToJoiner, Sealed::Bundle, &sealed).is_err(), "SPAKE2 alone");
361        let other_classical = SessionKeys::derive(b"other", [4; 32]);
362        assert!(other_classical.hybrid(&pk, &ct, &ss).open(Dir::ShowerToJoiner, Sealed::Bundle, &sealed).is_err(), "ML-KEM alone");
363        assert!(classical.hybrid(&pk, &ct, &[0; 32]).open(Dir::ShowerToJoiner, Sealed::Bundle, &sealed).is_err());
364        let received = classical.hybrid(&pk, &ct, &seed.decapsulate(&ct).unwrap());
365        assert_eq!(&*received.open(Dir::ShowerToJoiner, Sealed::Bundle, &sealed).unwrap(), b"identity");
366    }
367
368    /// libcrux against RustCrypto's independent FIPS 203 implementation, same seeds and randomness.
369    #[test]
370    fn ml_kem_matches_an_independent_implementation() {
371        use ml_kem::kem::Decapsulate;
372        use ml_kem::{EncapsulateDeterministic, EncodedSizeUser, KemCore, MlKem1024};
373        for i in 0..20u8 {
374            let mut seed = [0u8; 64];
375            rand::rngs::OsRng.fill_bytes(&mut seed);
376            seed[0] = i;
377            let ours = mlkem1024::generate_key_pair(seed);
378            let (d, z) = (seed[..32].try_into().unwrap(), seed[32..].try_into().unwrap());
379            let (dk, ek) = MlKem1024::generate_deterministic(&d, &z);
380            assert_eq!(ek.as_bytes().as_slice(), ours.pk().as_slice(), "encapsulation key");
381            assert_eq!(dk.as_bytes().as_slice(), ours.sk().as_slice(), "decapsulation key");
382
383            let mut m = [0u8; 32];
384            rand::rngs::OsRng.fill_bytes(&mut m);
385            let (ct, ss) = mlkem1024::encapsulate(ours.public_key(), m);
386            let (their_ct, their_ss) = ek.encapsulate_deterministic(&m.into()).unwrap();
387            assert_eq!(their_ct.as_slice(), ct.as_slice(), "ciphertext");
388            assert_eq!(their_ss.as_slice(), ss.as_slice(), "shared secret");
389            assert_eq!(dk.decapsulate(&their_ct).unwrap().as_slice(), mlkem1024::decapsulate(ours.private_key(), &ct).as_slice());
390        }
391    }
392
393    #[test]
394    fn the_room_depends_on_the_nameplate_only() {
395        assert_eq!(room(7), room(7));
396        assert_ne!(room(7), room(8));
397    }
398}