#![allow(clippy::arithmetic_side_effects)]
use elliptic_curve::ops::Reduce;
use elliptic_curve::sec1::ToSec1Point as _;
use p256::{ProjectivePoint, Scalar, U256};
use super::rustcrypto::{hmac, kdf};
use super::{
GROUP_SIZE_BYTES, HASH_LEN_BYTES, PUBLIC_KEY_SIZE_BYTES, SYMMETRIC_KEY_LENGTH_BYTES, Secret,
W_SIZE_BYTES,
};
use crate::error::{Error, ErrorCode, Result};
const M_COMPRESSED: [u8; 33] = [
0x02, 0x88, 0x6e, 0x2f, 0x97, 0xac, 0xe4, 0x6e, 0x55, 0xba, 0x9d, 0xd7, 0x24, 0x25, 0x79, 0xf2,
0x99, 0x3b, 0x64, 0xe1, 0x6e, 0xf3, 0xdc, 0xab, 0x95, 0xaf, 0xd4, 0x97, 0x33, 0x3d, 0x8f, 0xa1,
0x2f,
];
const N_COMPRESSED: [u8; 33] = [
0x03, 0xd8, 0xbb, 0xd6, 0xc6, 0x39, 0xc6, 0x29, 0x37, 0xb0, 0x4d, 0x99, 0x7f, 0x38, 0xc3, 0x77,
0x07, 0x19, 0xc6, 0x29, 0xd7, 0x01, 0x4d, 0x49, 0xa2, 0x4b, 0x4f, 0x98, 0xba, 0xa1, 0x29, 0x2b,
0x49,
];
const CONTEXT_PREFIX: &[u8; 26] = b"CHIP PAKE V1 Commissioning";
const CONFIRMATION_KEYS_INFO: &[u8] = b"ConfirmationKeys";
pub type SharedSecret = Secret<{ HASH_LEN_BYTES / 2 }>;
pub type Confirmation = [u8; HASH_LEN_BYTES];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Spake2pVerifierData {
pub w0: [u8; GROUP_SIZE_BYTES],
pub l: [u8; PUBLIC_KEY_SIZE_BYTES],
}
impl Spake2pVerifierData {
pub const LEN: usize = GROUP_SIZE_BYTES + PUBLIC_KEY_SIZE_BYTES;
pub fn from_passcode(passcode: u32, salt: &[u8], iterations: u32) -> Result<Self> {
let (w0, w1) = w0_w1(passcode, salt, iterations)?;
let l_point = ProjectivePoint::GENERATOR * w1;
Ok(Self {
w0: w0.to_bytes().into(),
l: encode_point(&l_point)?,
})
}
#[must_use]
pub fn to_bytes(&self) -> [u8; Self::LEN] {
let mut out = [0u8; Self::LEN];
if let Some(slot) = out.get_mut(..GROUP_SIZE_BYTES) {
slot.copy_from_slice(&self.w0);
}
if let Some(slot) = out.get_mut(GROUP_SIZE_BYTES..) {
slot.copy_from_slice(&self.l);
}
out
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
let (Some(w0), Some(l)) = (
bytes.get(..GROUP_SIZE_BYTES),
bytes.get(GROUP_SIZE_BYTES..Self::LEN),
) else {
return Err(Error::new(ErrorCode::InvalidArgument));
};
let mut out = Self {
w0: [0; GROUP_SIZE_BYTES],
l: [0; PUBLIC_KEY_SIZE_BYTES],
};
out.w0.copy_from_slice(w0);
out.l.copy_from_slice(l);
canonical_scalar(&out.w0)?;
decode_point(&out.l)?;
Ok(out)
}
}
fn w0_w1(passcode: u32, salt: &[u8], iterations: u32) -> Result<(Scalar, Scalar)> {
let mut ws = [0u8; 2 * W_SIZE_BYTES];
super::rustcrypto::pbkdf(&passcode.to_le_bytes(), salt, iterations, &mut ws)?;
let (Some(w0s), Some(w1s)) = (ws.get(..W_SIZE_BYTES), ws.get(W_SIZE_BYTES..)) else {
return Err(Error::new(ErrorCode::Platform));
};
let result = (reduce_wide(w0s)?, reduce_wide(w1s)?);
use zeroize::Zeroize as _;
ws.zeroize();
Ok(result)
}
fn reduce_wide(bytes: &[u8]) -> Result<Scalar> {
let radix = Scalar::from(256u64);
let mut acc = Scalar::ZERO;
for byte in bytes {
acc = acc * radix + Scalar::from(u64::from(*byte));
}
Ok(acc)
}
fn m_point() -> Result<ProjectivePoint> {
decode_point(&M_COMPRESSED)
}
fn n_point() -> Result<ProjectivePoint> {
decode_point(&N_COMPRESSED)
}
fn decode_point(bytes: &[u8]) -> Result<ProjectivePoint> {
let Ok(key) = p256::PublicKey::from_sec1_bytes(bytes) else {
return Err(Error::new(ErrorCode::InvalidArgument));
};
Ok(key.to_projective())
}
fn encode_point(point: &ProjectivePoint) -> Result<[u8; PUBLIC_KEY_SIZE_BYTES]> {
let Ok(key) = p256::PublicKey::from_affine(point.to_affine()) else {
return Err(Error::new(ErrorCode::InvalidArgument));
};
let encoded = key.to_sec1_point(false);
let Ok(arr) = <[u8; PUBLIC_KEY_SIZE_BYTES]>::try_from(encoded.as_bytes()) else {
return Err(Error::new(ErrorCode::Platform));
};
Ok(arr)
}
fn tt_append(hasher: &mut super::rustcrypto::Hasher, value: &[u8]) {
hasher.update(&(value.len() as u64).to_le_bytes());
hasher.update(value);
}
#[allow(clippy::too_many_arguments)]
fn finish(
context: &[u8],
prover_identity: &[u8],
verifier_identity: &[u8],
pa: &[u8; PUBLIC_KEY_SIZE_BYTES],
pb: &[u8; PUBLIC_KEY_SIZE_BYTES],
z: &ProjectivePoint,
v: &ProjectivePoint,
w0: &Scalar,
) -> Result<Outcome> {
let mut tt = super::rustcrypto::Hasher::new();
tt_append(&mut tt, context);
tt_append(&mut tt, prover_identity);
tt_append(&mut tt, verifier_identity);
tt_append(&mut tt, &encode_point(&m_point()?)?);
tt_append(&mut tt, &encode_point(&n_point()?)?);
tt_append(&mut tt, pa);
tt_append(&mut tt, pb);
tt_append(&mut tt, &encode_point(z)?);
tt_append(&mut tt, &encode_point(v)?);
let w0_bytes: [u8; GROUP_SIZE_BYTES] = w0.to_bytes().into();
tt_append(&mut tt, &w0_bytes);
let digest = tt.finish();
let (Some(ka), Some(ke)) = (
digest.get(..SYMMETRIC_KEY_LENGTH_BYTES),
digest.get(SYMMETRIC_KEY_LENGTH_BYTES..),
) else {
return Err(Error::new(ErrorCode::Platform));
};
let mut kc = [0u8; 2 * SYMMETRIC_KEY_LENGTH_BYTES];
kdf(ka, &[], CONFIRMATION_KEYS_INFO, &mut kc)?;
let (Some(kca), Some(kcb)) = (
kc.get(..SYMMETRIC_KEY_LENGTH_BYTES),
kc.get(SYMMETRIC_KEY_LENGTH_BYTES..),
) else {
return Err(Error::new(ErrorCode::Platform));
};
let ca = hmac(kca, pb)?;
let cb = hmac(kcb, pa)?;
let mut shared = SharedSecret::zeroed();
shared.as_mut().copy_from_slice(ke);
use zeroize::Zeroize as _;
kc.zeroize();
Ok(Outcome { ca, cb, shared })
}
struct Outcome {
ca: Confirmation,
cb: Confirmation,
shared: SharedSecret,
}
#[must_use]
pub fn context(pbkdf_param_request: &[u8], pbkdf_param_response: &[u8]) -> [u8; HASH_LEN_BYTES] {
let mut h = super::rustcrypto::Hasher::new();
h.update(CONTEXT_PREFIX);
h.update(pbkdf_param_request);
h.update(pbkdf_param_response);
h.finish()
}
pub struct Spake2pProver {
w0: Scalar,
w1: Scalar,
x: Scalar,
pa: [u8; PUBLIC_KEY_SIZE_BYTES],
}
impl core::fmt::Debug for Spake2pProver {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Spake2pProver(<redacted>)")
}
}
impl Spake2pProver {
pub fn new(
passcode: u32,
salt: &[u8],
iterations: u32,
random: &[u8; GROUP_SIZE_BYTES],
) -> Result<Self> {
let (w0, w1) = w0_w1(passcode, salt, iterations)?;
let x = scalar_from_random(random)?;
let pa_point = ProjectivePoint::GENERATOR * x + m_point()? * w0;
Ok(Self {
w0,
w1,
x,
pa: encode_point(&pa_point)?,
})
}
pub fn from_parts(
w0: &[u8; GROUP_SIZE_BYTES],
w1: &[u8; GROUP_SIZE_BYTES],
x: &[u8; GROUP_SIZE_BYTES],
) -> Result<Self> {
let w0 = scalar_from_bytes(w0)?;
let w1 = scalar_from_bytes(w1)?;
let x = scalar_from_random(x)?;
let pa_point = ProjectivePoint::GENERATOR * x + m_point()? * w0;
Ok(Self {
w0,
w1,
x,
pa: encode_point(&pa_point)?,
})
}
#[must_use]
pub const fn pa(&self) -> &[u8; PUBLIC_KEY_SIZE_BYTES] {
&self.pa
}
pub fn finish(
&self,
pb: &[u8; PUBLIC_KEY_SIZE_BYTES],
context: &[u8],
) -> Result<(Confirmation, Confirmation, SharedSecret)> {
self.finish_with_identities(pb, context, &[], &[])
}
pub fn finish_with_identities(
&self,
pb: &[u8; PUBLIC_KEY_SIZE_BYTES],
context: &[u8],
prover_identity: &[u8],
verifier_identity: &[u8],
) -> Result<(Confirmation, Confirmation, SharedSecret)> {
let pb_point = decode_point(pb)?;
let y_minus = pb_point - n_point()? * self.w0;
let z = y_minus * self.x;
let v = y_minus * self.w1;
let out = finish(
context,
prover_identity,
verifier_identity,
&self.pa,
pb,
&z,
&v,
&self.w0,
)?;
Ok((out.ca, out.cb, out.shared))
}
}
pub struct Spake2pVerifier {
w0: Scalar,
l: ProjectivePoint,
y: Scalar,
pb: [u8; PUBLIC_KEY_SIZE_BYTES],
}
impl core::fmt::Debug for Spake2pVerifier {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Spake2pVerifier(<redacted>)")
}
}
impl Spake2pVerifier {
pub fn new(data: &Spake2pVerifierData, random: &[u8; GROUP_SIZE_BYTES]) -> Result<Self> {
let w0 = scalar_from_bytes(&data.w0)?;
let l = decode_point(&data.l)?;
let y = scalar_from_random(random)?;
let pb_point = ProjectivePoint::GENERATOR * y + n_point()? * w0;
Ok(Self {
w0,
l,
y,
pb: encode_point(&pb_point)?,
})
}
pub fn from_parts(
w0: &[u8; GROUP_SIZE_BYTES],
l: &[u8; PUBLIC_KEY_SIZE_BYTES],
y: &[u8; GROUP_SIZE_BYTES],
) -> Result<Self> {
Self::new(&Spake2pVerifierData { w0: *w0, l: *l }, y)
}
#[must_use]
pub const fn pb(&self) -> &[u8; PUBLIC_KEY_SIZE_BYTES] {
&self.pb
}
pub fn finish(
&self,
pa: &[u8; PUBLIC_KEY_SIZE_BYTES],
context: &[u8],
) -> Result<(Confirmation, Confirmation, SharedSecret)> {
self.finish_with_identities(pa, context, &[], &[])
}
pub fn finish_with_identities(
&self,
pa: &[u8; PUBLIC_KEY_SIZE_BYTES],
context: &[u8],
prover_identity: &[u8],
verifier_identity: &[u8],
) -> Result<(Confirmation, Confirmation, SharedSecret)> {
let pa_point = decode_point(pa)?;
let z = (pa_point - m_point()? * self.w0) * self.y;
let v = self.l * self.y;
let out = finish(
context,
prover_identity,
verifier_identity,
pa,
&self.pb,
&z,
&v,
&self.w0,
)?;
Ok((out.ca, out.cb, out.shared))
}
}
fn scalar_from_random(random: &[u8; GROUP_SIZE_BYTES]) -> Result<Scalar> {
let s = <Scalar as Reduce<U256>>::reduce(&U256::from_be_slice(random));
if s == Scalar::ZERO {
return Err(Error::new(ErrorCode::InvalidArgument));
}
Ok(s)
}
fn canonical_scalar(bytes: &[u8; GROUP_SIZE_BYTES]) -> Result<Scalar> {
use elliptic_curve::PrimeField as _;
let mut repr = p256::FieldBytes::default();
repr.copy_from_slice(bytes);
Option::<Scalar>::from(Scalar::from_repr(repr))
.ok_or_else(|| Error::new(ErrorCode::InvalidArgument))
}
fn scalar_from_bytes(bytes: &[u8; GROUP_SIZE_BYTES]) -> Result<Scalar> {
Ok(<Scalar as Reduce<U256>>::reduce(&U256::from_be_slice(
bytes,
)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::crypto::ct_eq;
const SALT: &[u8] = b"SPAKE2P Key Salt";
const ITERATIONS: u32 = 1_000;
fn run(passcode_prover: u32, passcode_verifier: u32) -> Result<(bool, bool)> {
let data = Spake2pVerifierData::from_passcode(passcode_verifier, SALT, ITERATIONS)?;
let prover = Spake2pProver::new(passcode_prover, SALT, ITERATIONS, &[7u8; 32])?;
let verifier = Spake2pVerifier::new(&data, &[9u8; 32])?;
let ctx = context(b"request", b"response");
let (p_ca, p_cb, p_ke) = prover.finish(verifier.pb(), &ctx)?;
let (v_ca, v_cb, v_ke) = verifier.finish(prover.pa(), &ctx)?;
let confirmed = ct_eq(&p_ca, &v_ca) && ct_eq(&p_cb, &v_cb);
Ok((confirmed, p_ke == v_ke))
}
#[test]
fn the_right_passcode_agrees_on_a_key() {
let (confirmed, same_key) = run(20_202_021, 20_202_021).expect("exchange");
assert!(confirmed, "confirmations must match");
assert!(same_key, "and both sides derive the same Ke");
}
#[test]
fn the_wrong_passcode_agrees_on_nothing() {
let (confirmed, same_key) = run(20_202_021, 12_345_678).expect("exchange");
assert!(!confirmed, "confirmations must not match");
assert!(!same_key, "and the keys must differ");
}
#[test]
fn the_context_binds_the_exchange() {
let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
let prover = Spake2pProver::new(20_202_021, SALT, ITERATIONS, &[7u8; 32]).expect("prover");
let verifier = Spake2pVerifier::new(&data, &[9u8; 32]).expect("verifier");
let (_, _, a) = prover
.finish(verifier.pb(), &context(b"request-1", b"response"))
.expect("finish");
let (_, _, b) = prover
.finish(verifier.pb(), &context(b"request-2", b"response"))
.expect("finish");
assert_ne!(a, b);
}
#[test]
fn different_ephemerals_give_different_keys() {
let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
let ctx = context(b"", b"");
let mut keys = heapless::Vec::<SharedSecret, 4>::new();
for seed in [1u8, 2, 3] {
let prover =
Spake2pProver::new(20_202_021, SALT, ITERATIONS, &[seed; 32]).expect("prover");
let verifier =
Spake2pVerifier::new(&data, &[seed.wrapping_add(50); 32]).expect("verifier");
let (_, _, ke) = verifier.finish(prover.pa(), &ctx).expect("finish");
let _ = keys.push(ke);
}
assert_ne!(keys[0], keys[1]);
assert_ne!(keys[1], keys[2]);
}
#[test]
fn the_verifier_never_holds_w1() {
let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
assert_eq!(data.to_bytes().len(), Spake2pVerifierData::LEN);
assert_eq!(data.l[0], 0x04, "L is an uncompressed point");
let round = Spake2pVerifierData::from_bytes(&data.to_bytes()).expect("round trip");
assert_eq!(round, data);
}
#[test]
fn verifier_data_is_deterministic_for_a_passcode() {
let a = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("a");
let b = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("b");
assert_eq!(a, b);
let c = Spake2pVerifierData::from_passcode(20_202_022, SALT, ITERATIONS).expect("c");
assert_ne!(a, c);
}
#[test]
fn the_salt_and_iterations_change_the_verifier() {
let a = Spake2pVerifierData::from_passcode(20_202_021, SALT, 1_000).expect("a");
let b = Spake2pVerifierData::from_passcode(20_202_021, SALT, 2_000).expect("b");
let c =
Spake2pVerifierData::from_passcode(20_202_021, b"another key salt", 1_000).expect("c");
assert_ne!(a, b);
assert_ne!(a, c);
}
#[test]
fn a_point_that_is_not_on_the_curve_is_refused() {
let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
let verifier = Spake2pVerifier::new(&data, &[9u8; 32]).expect("verifier");
let mut bad = *verifier.pb();
bad[40] ^= 0xFF;
assert!(verifier.finish(&bad, &context(b"", b"")).is_err());
}
#[test]
fn a_zero_ephemeral_is_refused() {
let data = Spake2pVerifierData::from_passcode(20_202_021, SALT, ITERATIONS).expect("data");
assert!(
Spake2pVerifier::new(&data, &[0u8; 32]).is_err(),
"y = 0 makes pB = w0·N and leaks the exchange"
);
assert!(Spake2pProver::new(20_202_021, SALT, ITERATIONS, &[0u8; 32]).is_err());
}
#[test]
fn the_passcode_is_encoded_little_endian() {
assert_eq!(18_924_017u32.to_le_bytes(), [0xf1, 0xc1, 0x20, 0x01]);
assert_eq!(5u32.to_le_bytes(), [0x05, 0x00, 0x00, 0x00]);
}
#[test]
fn m_and_n_are_on_the_curve() {
assert!(m_point().is_ok());
assert!(n_point().is_ok());
assert_ne!(
encode_point(&m_point().expect("m")).expect("enc"),
encode_point(&n_point().expect("n")).expect("enc")
);
}
#[test]
fn wide_reduction_is_horners_method() {
assert_eq!(reduce_wide(&[0, 0, 1]).expect("r"), Scalar::from(1u64));
assert_eq!(reduce_wide(&[1, 0]).expect("r"), Scalar::from(256u64));
assert_eq!(reduce_wide(&[]).expect("r"), Scalar::ZERO);
}
}