Skip to main content

matter_kit/crypto/
spake2p.rs

1//! SPAKE2+, the password-authenticated key exchange PASE is built on (Core §3.10).
2//!
3//! A commissioner knows an eight-digit passcode printed on the device. SPAKE2+ turns that
4//! into a strong shared key without ever putting the passcode on the wire, and without
5//! letting an eavesdropper — or a man in the middle — learn anything they could test
6//! offline. An attacker gets **one guess per exchange**, which is what makes a
7//! twenty-seven-bit secret usable at all.
8//!
9//! The asymmetry matters and Matter fixes which side is which: "The SPAKE2+ verifier is
10//! the Commissionee/Responder and the SPAKE2+ prover is the Commissioner/Initiator."
11//! The device stores `(w0, L)` — from which the passcode cannot be recovered cheaply — and
12//! never stores `w1`. So reading a device's flash does not give you the passcode, and
13//! therefore does not let you impersonate the *commissioner* to another device.
14//!
15//! ```text
16//! prover (commissioner)                      verifier (commissionee)
17//!   w0, w1 = PBKDF(passcode, salt, iters)      w0, L = w1·P        (stored, no w1)
18//!   x ← random                                 y ← random
19//!   pA = x·P + w0·M            ── pA ──▶
20//!                              ◀── pB ──       pB = y·P + w0·N
21//!   Z = x·(pB − w0·N)                          Z = y·(pA − w0·M)
22//!   V = w1·(pB − w0·N)                         V = y·L
23//!                    both derive Ka‖Ke = Hash(TT)
24//!   cA = HMAC(KcA, pB)         ── cA ──▶       (checked)
25//!                              ◀── cB ──       cB = HMAC(KcB, pA)
26//! ```
27//!
28//! # A place where the specification and the SDK disagree
29//!
30//! §3.10 writes the confirmation-key derivation as `KDF(nil, Ka, "ConfirmationKeys")` and
31//! separately defines `KDF(info, key, salt)`. Read positionally, that makes
32//! `"ConfirmationKeys"` the **salt**. The SPAKE2+ draft the section cites defines its KDF
33//! as `KDF(salt, ikm, info)`, which makes it the **info** — and that is what the CHIP SDK
34//! computes, so it is what every deployed device computes.
35//!
36//! This crate follows the SDK: `HKDF(ikm = Ka, salt = [], info = "ConfirmationKeys")`.
37//! Following the other reading would produce a stack that is self-consistent and cannot
38//! commission anything.
39
40// Group arithmetic is *modular and total*: `Scalar` addition and multiplication are taken
41// modulo the group order, and point addition is closed over the curve. There is no
42// overflow for `arithmetic_side_effects` to warn about, and the types have no `checked_*`
43// variants to rewrite into — a scalar has no "too large" value. The denial stays in force
44// for every module that does arithmetic on values off the wire.
45#![allow(clippy::arithmetic_side_effects)]
46
47use elliptic_curve::ops::Reduce;
48use elliptic_curve::sec1::ToSec1Point as _;
49use p256::{ProjectivePoint, Scalar, U256};
50
51use super::rustcrypto::{hmac, kdf};
52use super::{
53    GROUP_SIZE_BYTES, HASH_LEN_BYTES, PUBLIC_KEY_SIZE_BYTES, SYMMETRIC_KEY_LENGTH_BYTES, Secret,
54    W_SIZE_BYTES,
55};
56use crate::error::{Error, ErrorCode, Result};
57
58/// `M`, in compressed SEC 1 form — "taken from the draft version 2 of the SPAKE2+
59/// specification" (§3.10).
60const M_COMPRESSED: [u8; 33] = [
61    0x02, 0x88, 0x6e, 0x2f, 0x97, 0xac, 0xe4, 0x6e, 0x55, 0xba, 0x9d, 0xd7, 0x24, 0x25, 0x79, 0xf2,
62    0x99, 0x3b, 0x64, 0xe1, 0x6e, 0xf3, 0xdc, 0xab, 0x95, 0xaf, 0xd4, 0x97, 0x33, 0x3d, 0x8f, 0xa1,
63    0x2f,
64];
65
66/// `N`, in compressed SEC 1 form (§3.10).
67const N_COMPRESSED: [u8; 33] = [
68    0x03, 0xd8, 0xbb, 0xd6, 0xc6, 0x39, 0xc6, 0x29, 0x37, 0xb0, 0x4d, 0x99, 0x7f, 0x38, 0xc3, 0x77,
69    0x07, 0x19, 0xc6, 0x29, 0xd7, 0x01, 0x4d, 0x49, 0xa2, 0x4b, 0x4f, 0x98, 0xba, 0xa1, 0x29, 0x2b,
70    0x49,
71];
72
73/// "CHIP PAKE V1 Commissioning" — §3.10.3.
74///
75/// "The usage of CHIP here is intentional and due to implementation in the SDK before the
76/// name change, should not be renamed to Matter."
77const CONTEXT_PREFIX: &[u8; 26] = b"CHIP PAKE V1 Commissioning";
78
79/// The `info` of the confirmation-key derivation. See the module note on why this is the
80/// info and not the salt.
81const CONFIRMATION_KEYS_INFO: &[u8] = b"ConfirmationKeys";
82
83/// `Ke`, the shared secret SPAKE2+ produces — `CRYPTO_HASH_LEN_BYTES / 2` octets (§3.10.4).
84pub type SharedSecret = Secret<{ HASH_LEN_BYTES / 2 }>;
85
86/// A confirmation value, `cA` or `cB` (§3.10.4).
87pub type Confirmation = [u8; HASH_LEN_BYTES];
88
89/// What a commissionee stores instead of the passcode: `(w0, L)` (§3.10).
90///
91/// "When the computation of `Crypto_PAKEValues_Responder` is done, fields `w0` and `L`
92/// SHALL be stored in the Responder and `w1` SHALL NOT be stored in the Responder."
93///
94/// This is what goes into a device's factory data. It is 87 octets and it is *not* secret
95/// in the way a private key is — but it is not public either: anyone holding it can
96/// impersonate the device to a commissioner, so it is protected like a credential.
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct Spake2pVerifierData {
99    /// `w0` — a scalar, big-endian.
100    pub w0: [u8; GROUP_SIZE_BYTES],
101    /// `L = w1 · P` — an uncompressed point.
102    pub l: [u8; PUBLIC_KEY_SIZE_BYTES],
103}
104
105impl Spake2pVerifierData {
106    /// The size of the serialised form: `w0 || L`.
107    pub const LEN: usize = GROUP_SIZE_BYTES + PUBLIC_KEY_SIZE_BYTES;
108
109    /// Computes `(w0, L)` from a passcode, as a factory-provisioning step would.
110    ///
111    /// `passcode` is the §5.1.1.6 passcode; the PBKDF input is its **little-endian**
112    /// 4-octet encoding — "passcode 18924017 would be encoded as the octet string
113    /// f1:c1:20:01".
114    pub fn from_passcode(passcode: u32, salt: &[u8], iterations: u32) -> Result<Self> {
115        let (w0, w1) = w0_w1(passcode, salt, iterations)?;
116        // L = w1 · P.
117        let l_point = ProjectivePoint::GENERATOR * w1;
118        Ok(Self {
119            w0: w0.to_bytes().into(),
120            l: encode_point(&l_point)?,
121        })
122    }
123
124    /// Serialises as `w0 || L`.
125    #[must_use]
126    pub fn to_bytes(&self) -> [u8; Self::LEN] {
127        let mut out = [0u8; Self::LEN];
128        // Both slices are of known length and `out` is exactly their sum.
129        if let Some(slot) = out.get_mut(..GROUP_SIZE_BYTES) {
130            slot.copy_from_slice(&self.w0);
131        }
132        if let Some(slot) = out.get_mut(GROUP_SIZE_BYTES..) {
133            slot.copy_from_slice(&self.l);
134        }
135        out
136    }
137
138    /// Reads `w0 || L`, checking that both halves are what they claim to be.
139    ///
140    /// The validation is not decoration. §11.19.8.1's `OpenCommissioningWindow` accepts a
141    /// verifier **from an administrator over the wire** and must answer `PAKEParameterError`
142    /// for one that is "incorrectly formatted or otherwise invalid" — and a verifier that was
143    /// only length-checked would be accepted here and fail much later, inside PASE, as an
144    /// inexplicable handshake failure that no commissioner could diagnose.
145    ///
146    /// `L` goes through the same point decoding every peer-supplied point does: it must be on
147    /// the curve and must not be the identity. The first is what stops an invalid-curve
148    /// attack; the second is what stops a verifier that would make every `Z` the identity and
149    /// every session key a constant. `w0` must be a canonical scalar below the group order —
150    /// a reduced-mod-`n` copy of an out-of-range value would be a *different* verifier that
151    /// re-encodes to different bytes.
152    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
153        let (Some(w0), Some(l)) = (
154            bytes.get(..GROUP_SIZE_BYTES),
155            bytes.get(GROUP_SIZE_BYTES..Self::LEN),
156        ) else {
157            return Err(Error::new(ErrorCode::InvalidArgument));
158        };
159        let mut out = Self {
160            w0: [0; GROUP_SIZE_BYTES],
161            l: [0; PUBLIC_KEY_SIZE_BYTES],
162        };
163        out.w0.copy_from_slice(w0);
164        out.l.copy_from_slice(l);
165        canonical_scalar(&out.w0)?;
166        decode_point(&out.l)?;
167        Ok(out)
168    }
169}
170
171/// `Crypto_PAKEValues_Initiator` — derives `(w0, w1)` from a passcode (§3.10).
172fn w0_w1(passcode: u32, salt: &[u8], iterations: u32) -> Result<(Scalar, Scalar)> {
173    let mut ws = [0u8; 2 * W_SIZE_BYTES];
174    // "passcode … serialized as little-endian over 4 octets".
175    super::rustcrypto::pbkdf(&passcode.to_le_bytes(), salt, iterations, &mut ws)?;
176
177    let (Some(w0s), Some(w1s)) = (ws.get(..W_SIZE_BYTES), ws.get(W_SIZE_BYTES..)) else {
178        return Err(Error::new(ErrorCode::Platform));
179    };
180    let result = (reduce_wide(w0s)?, reduce_wide(w1s)?);
181
182    // The PBKDF output is passcode-equivalent material; it does not outlive this call.
183    use zeroize::Zeroize as _;
184    ws.zeroize();
185    Ok(result)
186}
187
188/// Reduces a big-endian integer wider than a scalar, modulo the group order.
189///
190/// `w0s` and `w1s` are `CRYPTO_GROUP_SIZE_BYTES + 8` octets and the specification says
191/// `w0 = w0s mod p`. Horner's method over the octets does it in constant time with only
192/// scalar arithmetic — no wide-integer type, no branch on the value, and obviously correct
193/// at the cost of forty multiplications that happen once per commissioning.
194fn reduce_wide(bytes: &[u8]) -> Result<Scalar> {
195    let radix = Scalar::from(256u64);
196    let mut acc = Scalar::ZERO;
197    for byte in bytes {
198        acc = acc * radix + Scalar::from(u64::from(*byte));
199    }
200    Ok(acc)
201    // `Scalar: From<u64>` reduces nothing — every `u64` is already a valid scalar — and
202    // the multiply-add is modular, so the whole loop is a reduction by construction.
203}
204
205fn m_point() -> Result<ProjectivePoint> {
206    decode_point(&M_COMPRESSED)
207}
208
209fn n_point() -> Result<ProjectivePoint> {
210    decode_point(&N_COMPRESSED)
211}
212
213/// Decodes a SEC 1 point, compressed or uncompressed.
214///
215/// `p256::PublicKey::from_sec1_bytes` is the right tool and not merely a convenient one:
216/// it rejects a point that is not on the curve *and* rejects the identity. The first check
217/// is what stops an invalid-curve attack — a peer offering an "x" that lies on a different,
218/// weaker curve and hoping the scalar multiplication proceeds anyway — and skipping it
219/// would leak the scalar it is multiplied by.
220fn decode_point(bytes: &[u8]) -> Result<ProjectivePoint> {
221    let Ok(key) = p256::PublicKey::from_sec1_bytes(bytes) else {
222        return Err(Error::new(ErrorCode::InvalidArgument));
223    };
224    Ok(key.to_projective())
225}
226
227/// Encodes a point as an uncompressed SEC 1 octet string.
228///
229/// Fails for the identity, which has no uncompressed encoding. No point this crate
230/// computes should be the identity, and one that is would otherwise become a one-octet
231/// "encoding" that silently shortens a transcript.
232fn encode_point(point: &ProjectivePoint) -> Result<[u8; PUBLIC_KEY_SIZE_BYTES]> {
233    let Ok(key) = p256::PublicKey::from_affine(point.to_affine()) else {
234        return Err(Error::new(ErrorCode::InvalidArgument));
235    };
236    let encoded = key.to_sec1_point(false);
237    let Ok(arr) = <[u8; PUBLIC_KEY_SIZE_BYTES]>::try_from(encoded.as_bytes()) else {
238        return Err(Error::new(ErrorCode::Platform));
239    };
240    Ok(arr)
241}
242
243/// Appends `lengthInBytes(x) || x` to the transcript, with the length as an 8-octet
244/// little-endian integer — "the SPAKE2+ specification indicates that we must include these
245/// length fields" (§3.10.3).
246fn tt_append(hasher: &mut super::rustcrypto::Hasher, value: &[u8]) {
247    hasher.update(&(value.len() as u64).to_le_bytes());
248    hasher.update(value);
249}
250
251/// The shared half of both roles: build TT, hash it, split out the keys and confirmations.
252#[allow(clippy::too_many_arguments)]
253fn finish(
254    context: &[u8],
255    prover_identity: &[u8],
256    verifier_identity: &[u8],
257    pa: &[u8; PUBLIC_KEY_SIZE_BYTES],
258    pb: &[u8; PUBLIC_KEY_SIZE_BYTES],
259    z: &ProjectivePoint,
260    v: &ProjectivePoint,
261    w0: &Scalar,
262) -> Result<Outcome> {
263    let mut tt = super::rustcrypto::Hasher::new();
264    tt_append(&mut tt, context);
265    // SPAKE2+ puts both identities here. Matter uses neither — "the two
266    // 0x0000000000000000 null-lengths indicate that no identities are present" — and an
267    // absent identity is still a length field, which is why they cannot simply be
268    // omitted.
269    tt_append(&mut tt, prover_identity);
270    tt_append(&mut tt, verifier_identity);
271    tt_append(&mut tt, &encode_point(&m_point()?)?);
272    tt_append(&mut tt, &encode_point(&n_point()?)?);
273    tt_append(&mut tt, pa);
274    tt_append(&mut tt, pb);
275    tt_append(&mut tt, &encode_point(z)?);
276    tt_append(&mut tt, &encode_point(v)?);
277    let w0_bytes: [u8; GROUP_SIZE_BYTES] = w0.to_bytes().into();
278    tt_append(&mut tt, &w0_bytes);
279
280    let digest = tt.finish();
281    let (Some(ka), Some(ke)) = (
282        digest.get(..SYMMETRIC_KEY_LENGTH_BYTES),
283        digest.get(SYMMETRIC_KEY_LENGTH_BYTES..),
284    ) else {
285        return Err(Error::new(ErrorCode::Platform));
286    };
287
288    // KcA || KcB = HKDF(ikm = Ka, salt = [], info = "ConfirmationKeys").
289    let mut kc = [0u8; 2 * SYMMETRIC_KEY_LENGTH_BYTES];
290    kdf(ka, &[], CONFIRMATION_KEYS_INFO, &mut kc)?;
291    let (Some(kca), Some(kcb)) = (
292        kc.get(..SYMMETRIC_KEY_LENGTH_BYTES),
293        kc.get(SYMMETRIC_KEY_LENGTH_BYTES..),
294    ) else {
295        return Err(Error::new(ErrorCode::Platform));
296    };
297
298    // "cA := CRYPTO_HMAC(KcA, pB) and cB := CRYPTO_HMAC(KcB, pA)".
299    let ca = hmac(kca, pb)?;
300    let cb = hmac(kcb, pa)?;
301
302    let mut shared = SharedSecret::zeroed();
303    shared.as_mut().copy_from_slice(ke);
304
305    use zeroize::Zeroize as _;
306    kc.zeroize();
307
308    Ok(Outcome { ca, cb, shared })
309}
310
311/// What both roles end up with.
312struct Outcome {
313    ca: Confirmation,
314    cb: Confirmation,
315    shared: SharedSecret,
316}
317
318/// Computes the `Context` of §3.10.3.
319///
320/// "in case PBKDFParamRequest and PBKDFParamResponse messages are not exchanged, they
321/// SHALL be replaced by empty strings" — which is what passing empty slices does.
322#[must_use]
323pub fn context(pbkdf_param_request: &[u8], pbkdf_param_response: &[u8]) -> [u8; HASH_LEN_BYTES] {
324    let mut h = super::rustcrypto::Hasher::new();
325    h.update(CONTEXT_PREFIX);
326    h.update(pbkdf_param_request);
327    h.update(pbkdf_param_response);
328    h.finish()
329}
330
331/// The prover: a commissioner that knows the passcode (§3.10).
332pub struct Spake2pProver {
333    w0: Scalar,
334    w1: Scalar,
335    x: Scalar,
336    pa: [u8; PUBLIC_KEY_SIZE_BYTES],
337}
338
339impl core::fmt::Debug for Spake2pProver {
340    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
341        f.write_str("Spake2pProver(<redacted>)")
342    }
343}
344
345impl Spake2pProver {
346    /// Starts an exchange from a passcode and the PBKDF parameters the device announced.
347    ///
348    /// `random` must be 32 octets of cryptographically secure randomness — the ephemeral
349    /// scalar `x`. A predictable `x` hands the session key to anyone watching.
350    pub fn new(
351        passcode: u32,
352        salt: &[u8],
353        iterations: u32,
354        random: &[u8; GROUP_SIZE_BYTES],
355    ) -> Result<Self> {
356        let (w0, w1) = w0_w1(passcode, salt, iterations)?;
357        let x = scalar_from_random(random)?;
358        // pA = x·P + w0·M
359        let pa_point = ProjectivePoint::GENERATOR * x + m_point()? * w0;
360        Ok(Self {
361            w0,
362            w1,
363            x,
364            pa: encode_point(&pa_point)?,
365        })
366    }
367
368    /// Starts an exchange from `w0` and `w1` directly.
369    ///
370    /// [`Spake2pProver::new`] derives those from a passcode, which is what a commissioner
371    /// reading a QR code does. This takes them ready-made — for a commissioner whose
372    /// PBKDF ran somewhere else, and for checking this implementation against the
373    /// published SPAKE2+ test vectors, which state `w0` and `w1` rather than a passcode.
374    pub fn from_parts(
375        w0: &[u8; GROUP_SIZE_BYTES],
376        w1: &[u8; GROUP_SIZE_BYTES],
377        x: &[u8; GROUP_SIZE_BYTES],
378    ) -> Result<Self> {
379        let w0 = scalar_from_bytes(w0)?;
380        let w1 = scalar_from_bytes(w1)?;
381        let x = scalar_from_random(x)?;
382        let pa_point = ProjectivePoint::GENERATOR * x + m_point()? * w0;
383        Ok(Self {
384            w0,
385            w1,
386            x,
387            pa: encode_point(&pa_point)?,
388        })
389    }
390
391    /// `pA`, to send to the commissionee.
392    #[must_use]
393    pub const fn pa(&self) -> &[u8; PUBLIC_KEY_SIZE_BYTES] {
394        &self.pa
395    }
396
397    /// Given the commissionee's `pB`, derives the keys and the confirmations.
398    ///
399    /// Returns `(cA to send, cB to expect, Ke)`. The caller must compare the peer's `cB`
400    /// against the returned one with [`ct_eq`](super::ct_eq), and abandon the session if
401    /// it differs: that comparison is the only thing standing between a correct passcode
402    /// and a wrong one.
403    pub fn finish(
404        &self,
405        pb: &[u8; PUBLIC_KEY_SIZE_BYTES],
406        context: &[u8],
407    ) -> Result<(Confirmation, Confirmation, SharedSecret)> {
408        self.finish_with_identities(pb, context, &[], &[])
409    }
410
411    /// [`Spake2pProver::finish`] with explicit SPAKE2+ identities.
412    ///
413    /// Matter uses neither identity, so [`Spake2pProver::finish`] is what a Matter
414    /// commissioner calls. This exists because SPAKE2+ itself has them, and because the
415    /// specification's own published test vectors exercise all four combinations — being
416    /// able to run those is the difference between "our two halves agree" and "our
417    /// arithmetic is right".
418    pub fn finish_with_identities(
419        &self,
420        pb: &[u8; PUBLIC_KEY_SIZE_BYTES],
421        context: &[u8],
422        prover_identity: &[u8],
423        verifier_identity: &[u8],
424    ) -> Result<(Confirmation, Confirmation, SharedSecret)> {
425        // `decode_point` has already rejected an off-curve point and the identity.
426        let pb_point = decode_point(pb)?;
427        // Y − w0·N
428        let y_minus = pb_point - n_point()? * self.w0;
429        let z = y_minus * self.x;
430        let v = y_minus * self.w1;
431        let out = finish(
432            context,
433            prover_identity,
434            verifier_identity,
435            &self.pa,
436            pb,
437            &z,
438            &v,
439            &self.w0,
440        )?;
441        Ok((out.ca, out.cb, out.shared))
442    }
443}
444
445/// The verifier: a commissionee that stores `(w0, L)` and never saw `w1` (§3.10).
446pub struct Spake2pVerifier {
447    w0: Scalar,
448    l: ProjectivePoint,
449    y: Scalar,
450    pb: [u8; PUBLIC_KEY_SIZE_BYTES],
451}
452
453impl core::fmt::Debug for Spake2pVerifier {
454    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
455        f.write_str("Spake2pVerifier(<redacted>)")
456    }
457}
458
459impl Spake2pVerifier {
460    /// Starts an exchange from stored verifier data.
461    ///
462    /// `random` must be 32 octets of cryptographically secure randomness — the ephemeral
463    /// scalar `y`.
464    pub fn new(data: &Spake2pVerifierData, random: &[u8; GROUP_SIZE_BYTES]) -> Result<Self> {
465        let w0 = scalar_from_bytes(&data.w0)?;
466        let l = decode_point(&data.l)?;
467        let y = scalar_from_random(random)?;
468        // pB = y·P + w0·N
469        let pb_point = ProjectivePoint::GENERATOR * y + n_point()? * w0;
470        Ok(Self {
471            w0,
472            l,
473            y,
474            pb: encode_point(&pb_point)?,
475        })
476    }
477
478    /// Starts an exchange from `w0` and `L` directly, with an explicit `y`.
479    ///
480    /// The counterpart of [`Spake2pProver::from_parts`], and what the published test
481    /// vectors need.
482    pub fn from_parts(
483        w0: &[u8; GROUP_SIZE_BYTES],
484        l: &[u8; PUBLIC_KEY_SIZE_BYTES],
485        y: &[u8; GROUP_SIZE_BYTES],
486    ) -> Result<Self> {
487        Self::new(&Spake2pVerifierData { w0: *w0, l: *l }, y)
488    }
489
490    /// `pB`, to send to the commissioner.
491    #[must_use]
492    pub const fn pb(&self) -> &[u8; PUBLIC_KEY_SIZE_BYTES] {
493        &self.pb
494    }
495
496    /// Given the commissioner's `pA`, derives the keys and the confirmations.
497    ///
498    /// Returns `(cA to expect, cB to send, Ke)`.
499    pub fn finish(
500        &self,
501        pa: &[u8; PUBLIC_KEY_SIZE_BYTES],
502        context: &[u8],
503    ) -> Result<(Confirmation, Confirmation, SharedSecret)> {
504        self.finish_with_identities(pa, context, &[], &[])
505    }
506
507    /// [`Spake2pVerifier::finish`] with explicit SPAKE2+ identities. See
508    /// [`Spake2pProver::finish_with_identities`].
509    pub fn finish_with_identities(
510        &self,
511        pa: &[u8; PUBLIC_KEY_SIZE_BYTES],
512        context: &[u8],
513        prover_identity: &[u8],
514        verifier_identity: &[u8],
515    ) -> Result<(Confirmation, Confirmation, SharedSecret)> {
516        let pa_point = decode_point(pa)?;
517        // Z = y·(X − w0·M), V = y·L
518        let z = (pa_point - m_point()? * self.w0) * self.y;
519        let v = self.l * self.y;
520        let out = finish(
521            context,
522            prover_identity,
523            verifier_identity,
524            pa,
525            &self.pb,
526            &z,
527            &v,
528            &self.w0,
529        )?;
530        Ok((out.ca, out.cb, out.shared))
531    }
532}
533
534/// Turns 32 random octets into a scalar, refusing zero.
535///
536/// A zero ephemeral scalar makes `pA = w0·M`, from which an attacker who guesses `w0`
537/// learns everything. The probability of drawing zero from a good generator is negligible;
538/// the probability of a *broken* generator producing it is not.
539fn scalar_from_random(random: &[u8; GROUP_SIZE_BYTES]) -> Result<Scalar> {
540    let s = <Scalar as Reduce<U256>>::reduce(&U256::from_be_slice(random));
541    if s == Scalar::ZERO {
542        return Err(Error::new(ErrorCode::InvalidArgument));
543    }
544    Ok(s)
545}
546
547/// A scalar that must already be canonical — strictly below the group order.
548///
549/// [`scalar_from_bytes`] *reduces* instead, which is right where the value is derived rather
550/// than received: §3.10's `w0s mod p` cannot be out of range by construction. It is wrong for
551/// a value that arrived from a peer, because reducing accepts a verifier the sender never
552/// computed and makes the bytes and the scalar disagree — the stored `w0` would re-encode to
553/// something that is not what was checked.
554fn canonical_scalar(bytes: &[u8; GROUP_SIZE_BYTES]) -> Result<Scalar> {
555    use elliptic_curve::PrimeField as _;
556
557    let mut repr = p256::FieldBytes::default();
558    repr.copy_from_slice(bytes);
559    Option::<Scalar>::from(Scalar::from_repr(repr))
560        .ok_or_else(|| Error::new(ErrorCode::InvalidArgument))
561}
562
563fn scalar_from_bytes(bytes: &[u8; GROUP_SIZE_BYTES]) -> Result<Scalar> {
564    Ok(<Scalar as Reduce<U256>>::reduce(&U256::from_be_slice(
565        bytes,
566    )))
567}
568
569#[cfg(test)]
570mod tests {
571    use super::*;
572    use crate::crypto::ct_eq;
573
574    const SALT: &[u8] = b"SPAKE2P Key Salt";
575    const ITERATIONS: u32 = 1_000;
576
577    fn run(passcode_prover: u32, passcode_verifier: u32) -> Result<(bool, bool)> {
578        let data = Spake2pVerifierData::from_passcode(passcode_verifier, SALT, ITERATIONS)?;
579        let prover = Spake2pProver::new(passcode_prover, SALT, ITERATIONS, &[7u8; 32])?;
580        let verifier = Spake2pVerifier::new(&data, &[9u8; 32])?;
581
582        let ctx = context(b"request", b"response");
583        let (p_ca, p_cb, p_ke) = prover.finish(verifier.pb(), &ctx)?;
584        let (v_ca, v_cb, v_ke) = verifier.finish(prover.pa(), &ctx)?;
585
586        // The verifier checks the prover's cA; the prover checks the verifier's cB.
587        let confirmed = ct_eq(&p_ca, &v_ca) && ct_eq(&p_cb, &v_cb);
588        Ok((confirmed, p_ke == v_ke))
589    }
590
591    #[test]
592    fn the_right_passcode_agrees_on_a_key() {
593        let (confirmed, same_key) = run(20_202_021, 20_202_021).expect("exchange");
594        assert!(confirmed, "confirmations must match");
595        assert!(same_key, "and both sides derive the same Ke");
596    }
597
598    #[test]
599    fn the_wrong_passcode_agrees_on_nothing() {
600        // The whole point: one guess per exchange, and a wrong guess tells you only that
601        // it was wrong.
602        let (confirmed, same_key) = run(20_202_021, 12_345_678).expect("exchange");
603        assert!(!confirmed, "confirmations must not match");
604        assert!(!same_key, "and the keys must differ");
605    }
606
607    #[test]
608    fn the_context_binds_the_exchange() {
609        // Two runs that differ only in the PBKDFParamRequest must not produce the same
610        // key — that binding is what stops a transcript being replayed into another
611        // exchange.
612        let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
613        let prover = Spake2pProver::new(20_202_021, SALT, ITERATIONS, &[7u8; 32]).expect("prover");
614        let verifier = Spake2pVerifier::new(&data, &[9u8; 32]).expect("verifier");
615
616        let (_, _, a) = prover
617            .finish(verifier.pb(), &context(b"request-1", b"response"))
618            .expect("finish");
619        let (_, _, b) = prover
620            .finish(verifier.pb(), &context(b"request-2", b"response"))
621            .expect("finish");
622        assert_ne!(a, b);
623    }
624
625    #[test]
626    fn different_ephemerals_give_different_keys() {
627        let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
628        let ctx = context(b"", b"");
629
630        let mut keys = heapless::Vec::<SharedSecret, 4>::new();
631        for seed in [1u8, 2, 3] {
632            let prover =
633                Spake2pProver::new(20_202_021, SALT, ITERATIONS, &[seed; 32]).expect("prover");
634            let verifier =
635                Spake2pVerifier::new(&data, &[seed.wrapping_add(50); 32]).expect("verifier");
636            let (_, _, ke) = verifier.finish(prover.pa(), &ctx).expect("finish");
637            let _ = keys.push(ke);
638        }
639        assert_ne!(keys[0], keys[1]);
640        assert_ne!(keys[1], keys[2]);
641    }
642
643    #[test]
644    fn the_verifier_never_holds_w1() {
645        // The structural reason reading a device's flash does not yield the passcode:
646        // what is stored is w0 and L = w1·P, and recovering w1 from L is a discrete log.
647        let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
648        assert_eq!(data.to_bytes().len(), Spake2pVerifierData::LEN);
649        assert_eq!(data.l[0], 0x04, "L is an uncompressed point");
650
651        let round = Spake2pVerifierData::from_bytes(&data.to_bytes()).expect("round trip");
652        assert_eq!(round, data);
653    }
654
655    #[test]
656    fn verifier_data_is_deterministic_for_a_passcode() {
657        // A factory can compute it once and burn it in; a device can recompute it from the
658        // passcode. Both must agree.
659        let a = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("a");
660        let b = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("b");
661        assert_eq!(a, b);
662        let c = Spake2pVerifierData::from_passcode(20_202_022, SALT, ITERATIONS).expect("c");
663        assert_ne!(a, c);
664    }
665
666    #[test]
667    fn the_salt_and_iterations_change_the_verifier() {
668        let a = Spake2pVerifierData::from_passcode(20_202_021, SALT, 1_000).expect("a");
669        let b = Spake2pVerifierData::from_passcode(20_202_021, SALT, 2_000).expect("b");
670        let c =
671            Spake2pVerifierData::from_passcode(20_202_021, b"another key salt", 1_000).expect("c");
672        assert_ne!(a, b);
673        assert_ne!(a, c);
674    }
675
676    #[test]
677    fn a_point_that_is_not_on_the_curve_is_refused() {
678        // An invalid-curve attack starts here: a peer sends a "point" whose x is on a
679        // different, weaker curve, and hopes the scalar multiplication proceeds anyway.
680        let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
681        let verifier = Spake2pVerifier::new(&data, &[9u8; 32]).expect("verifier");
682        let mut bad = *verifier.pb();
683        bad[40] ^= 0xFF;
684        assert!(verifier.finish(&bad, &context(b"", b"")).is_err());
685    }
686
687    #[test]
688    fn a_zero_ephemeral_is_refused() {
689        let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
690        assert!(
691            Spake2pVerifier::new(&data, &[0u8; 32]).is_err(),
692            "y = 0 makes pB = w0·N and leaks the exchange"
693        );
694        assert!(Spake2pProver::new(20_202_021, SALT, ITERATIONS, &[0u8; 32]).is_err());
695    }
696
697    #[test]
698    fn the_passcode_is_encoded_little_endian() {
699        // §3.10: "passcode 18924017 would be encoded as the octet string f1:c1:20:01".
700        assert_eq!(18_924_017u32.to_le_bytes(), [0xf1, 0xc1, 0x20, 0x01]);
701        assert_eq!(5u32.to_le_bytes(), [0x05, 0x00, 0x00, 0x00]);
702    }
703
704    #[test]
705    fn m_and_n_are_on_the_curve() {
706        // If either constant were mistyped the exchange would simply never agree, with no
707        // other symptom, so check them directly.
708        assert!(m_point().is_ok());
709        assert!(n_point().is_ok());
710        assert_ne!(
711            encode_point(&m_point().expect("m")).expect("enc"),
712            encode_point(&n_point().expect("n")).expect("enc")
713        );
714    }
715
716    #[test]
717    fn wide_reduction_is_horners_method() {
718        // Small values reduce to themselves.
719        assert_eq!(reduce_wide(&[0, 0, 1]).expect("r"), Scalar::from(1u64));
720        assert_eq!(reduce_wide(&[1, 0]).expect("r"), Scalar::from(256u64));
721        assert_eq!(reduce_wide(&[]).expect("r"), Scalar::ZERO);
722    }
723}