#[cfg(test)]
mod tests;
use alloc::vec::Vec;
use curve25519_dalek::edwards::{CompressedEdwardsY, EdwardsPoint};
use curve25519_dalek::scalar::Scalar;
use curve25519_dalek::traits::Identity;
use rsa::rand_core::CryptoRngCore;
use rsa::sha2::{Digest, Sha512};
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use zeroize::Zeroizing;
const M_BYTES: [u8; 32] = [
0x5a, 0xda, 0x7e, 0x4b, 0xf6, 0xdd, 0xd9, 0xad, 0xb6, 0x62, 0x6d, 0x32, 0x13, 0x1c, 0x6b, 0x5c,
0x51, 0xa1, 0xe3, 0x47, 0xa3, 0x47, 0x8f, 0x53, 0xcf, 0xcf, 0x44, 0x1b, 0x88, 0xee, 0xd1, 0x2e,
];
const N_BYTES: [u8; 32] = [
0x10, 0xe3, 0xdf, 0x0a, 0xe3, 0x7d, 0x8e, 0x7a, 0x99, 0xb5, 0xfe, 0x74, 0xb4, 0x46, 0x72, 0x10,
0x3d, 0xbd, 0xdc, 0xbd, 0x06, 0xaf, 0x68, 0x0d, 0x71, 0x32, 0x9a, 0x11, 0x69, 0x3b, 0xc7, 0x78,
];
const ORDER: [u8; 32] = [
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Role {
Alice,
Bob,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Spake2Error {
MessageLength(usize),
NotAPoint,
}
impl core::fmt::Display for Spake2Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::MessageLength(n) => write!(f, "spake2 message is {n} bytes, not 32"),
Self::NotAPoint => f.write_str("spake2 message does not decode to a curve point"),
}
}
}
impl core::error::Error for Spake2Error {}
fn add_assign(a: &mut [u8; 32], b: &[u8; 32]) {
let mut carry = 0u16;
for i in 0..32 {
let sum = u16::from(a[i]) + u16::from(b[i]) + carry;
a[i] = sum as u8;
carry = sum >> 8;
}
}
fn double_assign(a: &mut [u8; 32]) {
let copy = *a;
add_assign(a, ©);
}
fn left_shift_3(n: &mut [u8; 32]) {
let mut carry = 0u8;
for byte in n.iter_mut() {
let next = *byte >> 5;
*byte = (*byte << 3) | carry;
carry = next;
}
}
fn mul_raw(point: &EdwardsPoint, scalar: &[u8; 32]) -> EdwardsPoint {
let mut acc = EdwardsPoint::identity();
for byte in scalar.iter().rev() {
for bit in (0..8).rev() {
acc = acc + acc;
let sum = acc + point;
let take = Choice::from((byte >> bit) & 1);
acc = EdwardsPoint::conditional_select(&acc, &sum, take);
}
}
acc
}
fn reduce_wide(wide: &[u8; 64]) -> [u8; 32] {
Scalar::from_bytes_mod_order_wide(wide).to_bytes()
}
fn absorb(hash: &mut Sha512, data: &[u8]) {
hash.update((data.len() as u64).to_le_bytes());
hash.update(data);
}
pub struct Spake2 {
role: Role,
my_name: Vec<u8>,
their_name: Vec<u8>,
private_key: Zeroizing<[u8; 32]>,
password_hash: Zeroizing<[u8; 64]>,
password_scalar: Zeroizing<[u8; 32]>,
my_msg: [u8; 32],
}
impl Spake2 {
pub fn new<R: CryptoRngCore>(
role: Role,
my_name: &[u8],
their_name: &[u8],
password: &[u8],
rng: &mut R,
) -> Self {
let mut wide = Zeroizing::new([0u8; 64]);
rng.fill_bytes(wide.as_mut());
let mut private_key = Zeroizing::new(reduce_wide(&wide));
left_shift_3(&mut private_key);
let password_hash = Zeroizing::new(Sha512::digest(password).into());
let password_scalar = Zeroizing::new(Self::password_scalar(&password_hash));
let mask = match role {
Role::Alice => Self::point(&M_BYTES),
Role::Bob => Self::point(&N_BYTES),
};
let base = EdwardsPoint::mul_base(&Scalar::from_bytes_mod_order(*private_key));
let my_msg = (base + mul_raw(&mask, &password_scalar))
.compress()
.to_bytes();
Self {
role,
my_name: my_name.into(),
their_name: their_name.into(),
private_key,
password_hash,
password_scalar,
my_msg,
}
}
pub fn message(&self) -> &[u8; 32] {
&self.my_msg
}
pub fn finish(self, their_msg: &[u8; 32]) -> Result<Zeroizing<[u8; 64]>, Spake2Error> {
let masked = CompressedEdwardsY(*their_msg)
.decompress()
.ok_or(Spake2Error::NotAPoint)?;
let peer_mask = match self.role {
Role::Alice => Self::point(&N_BYTES),
Role::Bob => Self::point(&M_BYTES),
};
let unmasked = masked - mul_raw(&peer_mask, &self.password_scalar);
let shared = Zeroizing::new(mul_raw(&unmasked, &self.private_key).compress().to_bytes());
let (alice_name, bob_name, alice_msg, bob_msg) = match self.role {
Role::Alice => (&self.my_name, &self.their_name, &self.my_msg, their_msg),
Role::Bob => (&self.their_name, &self.my_name, their_msg, &self.my_msg),
};
let mut hash = Sha512::new();
absorb(&mut hash, alice_name);
absorb(&mut hash, bob_name);
absorb(&mut hash, alice_msg);
absorb(&mut hash, bob_msg);
absorb(&mut hash, shared.as_ref());
absorb(&mut hash, self.password_hash.as_ref());
Ok(Zeroizing::new(hash.finalize().into()))
}
fn password_scalar(password_hash: &[u8; 64]) -> [u8; 32] {
let mut scalar = reduce_wide(password_hash);
let mut order = ORDER;
for bit in 0..3u32 {
let mask = 1u8 << bit;
let set = (scalar[0] & mask).ct_eq(&mask);
let mut addend = [0u8; 32];
for (dst, src) in addend.iter_mut().zip(order.iter()) {
*dst = u8::conditional_select(&0, src, set);
}
add_assign(&mut scalar, &addend);
double_assign(&mut order);
}
debug_assert_eq!(scalar[0] & 7, 0);
scalar
}
fn point(bytes: &[u8; 32]) -> EdwardsPoint {
CompressedEdwardsY(*bytes)
.decompress()
.expect("M and N are curve points, checked by a test")
}
}