1#![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
58const 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
66const 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
73const CONTEXT_PREFIX: &[u8; 26] = b"CHIP PAKE V1 Commissioning";
78
79const CONFIRMATION_KEYS_INFO: &[u8] = b"ConfirmationKeys";
82
83pub type SharedSecret = Secret<{ HASH_LEN_BYTES / 2 }>;
85
86pub type Confirmation = [u8; HASH_LEN_BYTES];
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub struct Spake2pVerifierData {
99 pub w0: [u8; GROUP_SIZE_BYTES],
101 pub l: [u8; PUBLIC_KEY_SIZE_BYTES],
103}
104
105impl Spake2pVerifierData {
106 pub const LEN: usize = GROUP_SIZE_BYTES + PUBLIC_KEY_SIZE_BYTES;
108
109 pub fn from_passcode(passcode: u32, salt: &[u8], iterations: u32) -> Result<Self> {
115 let (w0, w1) = w0_w1(passcode, salt, iterations)?;
116 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 #[must_use]
126 pub fn to_bytes(&self) -> [u8; Self::LEN] {
127 let mut out = [0u8; Self::LEN];
128 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 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
171fn w0_w1(passcode: u32, salt: &[u8], iterations: u32) -> Result<(Scalar, Scalar)> {
173 let mut ws = [0u8; 2 * W_SIZE_BYTES];
174 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 use zeroize::Zeroize as _;
184 ws.zeroize();
185 Ok(result)
186}
187
188fn 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 }
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
213fn 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
227fn 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
243fn 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#[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 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 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 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
311struct Outcome {
313 ca: Confirmation,
314 cb: Confirmation,
315 shared: SharedSecret,
316}
317
318#[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
331pub 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 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 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 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 #[must_use]
393 pub const fn pa(&self) -> &[u8; PUBLIC_KEY_SIZE_BYTES] {
394 &self.pa
395 }
396
397 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 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 let pb_point = decode_point(pb)?;
427 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
445pub 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 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 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 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 #[must_use]
492 pub const fn pb(&self) -> &[u8; PUBLIC_KEY_SIZE_BYTES] {
493 &self.pb
494 }
495
496 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 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 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
534fn 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
547fn 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 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 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 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 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 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 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 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 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 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}