use anyhow::{bail, Result};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha512};
use subtle::ConstantTimeEq;
use zeroize::Zeroizing;
const DSI: &[u8] = b"CPace255";
const DSI_ISK: &[u8] = b"CPace255_ISK";
const MAC_LABEL: &[u8] = b"CPaceMac";
const SHA512_BLOCK_LEN: usize = 128;
pub const SHARE_LEN: usize = 32;
pub const ISK_LEN: usize = 64;
pub const TAG_LEN: usize = 64;
const FIELD_MODULUS: [u8; 32] = [
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
];
pub fn generator(prs: &[u8], ci: &[u8], sid: &[u8]) -> [u8; 32] {
let digest = Sha512::digest(generator_string(prs, ci, sid));
let mut field = [0u8; 32];
field.copy_from_slice(&digest[..32]);
map_to_curve(&field)
}
pub fn map_to_curve(field: &[u8; 32]) -> [u8; 32] {
let mut element = *field;
element[31] &= 0x7f;
elligator2::from_representative(&representative(element))
}
pub fn scalar_mult_vfy(scalar: &[u8; 32], u: &[u8; 32]) -> Result<[u8; 32]> {
let point = x25519_dalek::x25519(*scalar, *u);
if is_all_zero(&point) {
bail!("the peer's CPace share encodes a low-order point");
}
Ok(point)
}
fn is_all_zero(bytes: &[u8]) -> bool {
bytes.iter().fold(0u8, |acc, &byte| acc | byte) == 0
}
pub fn public_share(scalar: &[u8; 32], generator: &[u8; 32]) -> Result<[u8; 32]> {
scalar_mult_vfy(scalar, generator)
}
pub fn lv_cat(parts: &[&[u8]]) -> Vec<u8> {
let mut joined = Vec::new();
for part in parts {
push_lv(&mut joined, part);
}
joined
}
pub fn transcript_ir(ya: &[u8], ad_a: &[u8], yb: &[u8], ad_b: &[u8]) -> Vec<u8> {
let mut transcript = lv_cat(&[ya, ad_a]);
transcript.extend_from_slice(&lv_cat(&[yb, ad_b]));
transcript
}
pub fn transcript_oc(ya: &[u8], ad_a: &[u8], yb: &[u8], ad_b: &[u8]) -> Vec<u8> {
let initiator = lv_cat(&[ya, ad_a]);
let responder = lv_cat(&[yb, ad_b]);
let mut transcript = Vec::from(b"oc".as_slice());
if lexicographically_larger(&initiator, &responder) {
transcript.extend_from_slice(&initiator);
transcript.extend_from_slice(&responder);
} else {
transcript.extend_from_slice(&responder);
transcript.extend_from_slice(&initiator);
}
transcript
}
pub fn intermediate_session_key(
sid: &[u8],
shared_point: &[u8],
transcript: &[u8],
) -> [u8; ISK_LEN] {
let mut input = Zeroizing::new(lv_cat(&[DSI_ISK, sid, shared_point]));
input.extend_from_slice(transcript);
Sha512::digest(&input[..]).into()
}
pub fn key_confirmation_tag(
sid: &[u8],
isk: &[u8; ISK_LEN],
share: &[u8],
ad: &[u8],
) -> [u8; TAG_LEN] {
let mut key_input = Zeroizing::new(Vec::from(MAC_LABEL));
key_input.extend_from_slice(sid);
key_input.extend_from_slice(isk);
let mac_key = Zeroizing::new(<[u8; 64]>::from(Sha512::digest(&key_input[..])));
let mut mac = <Hmac<Sha512> as Mac>::new_from_slice(&mac_key[..])
.expect("HMAC-SHA-512 accepts a key of any length");
mac.update(&lv_cat(&[share, ad]));
mac.finalize().into_bytes().into()
}
#[must_use]
pub fn verify_key_confirmation_tag(expected: &[u8; TAG_LEN], received: &[u8; TAG_LEN]) -> bool {
bool::from(expected[..].ct_eq(&received[..]))
}
fn lexicographically_larger(left: &[u8], right: &[u8]) -> bool {
for (a, b) in left.iter().zip(right) {
if a > b {
return true;
}
if a < b {
return false;
}
}
left.len() > right.len()
}
fn generator_string(prs: &[u8], ci: &[u8], sid: &[u8]) -> Vec<u8> {
let pad = SHA512_BLOCK_LEN.saturating_sub(
1 + prepend_len_len(DSI.len()) + DSI.len() + prepend_len_len(prs.len()) + prs.len(),
);
let mut string = Vec::new();
push_lv(&mut string, DSI);
push_lv(&mut string, prs);
push_len(&mut string, pad);
string.resize(string.len() + pad, 0);
push_lv(&mut string, ci);
push_lv(&mut string, sid);
string
}
fn push_lv(out: &mut Vec<u8>, bytes: &[u8]) {
push_len(out, bytes.len());
out.extend_from_slice(bytes);
}
fn push_len(out: &mut Vec<u8>, mut len: usize) {
loop {
let byte = (len & 0x7f) as u8;
len >>= 7;
if len == 0 {
out.push(byte);
return;
}
out.push(byte | 0x80);
}
}
fn prepend_len_len(len: usize) -> usize {
let mut len = len;
let mut width = 1;
while len >= 0x80 {
len >>= 7;
width += 1;
}
width
}
fn representative(field: [u8; 32]) -> [u8; 32] {
let (reduced, borrow) = subtract(&field, &FIELD_MODULUS);
let reduced = select(&field, &reduced, borrow.wrapping_sub(1));
let (negated, _) = subtract(&FIELD_MODULUS, &reduced);
select(&reduced, &negated, 0u8.wrapping_sub(reduced[31] >> 6))
}
fn subtract(a: &[u8; 32], b: &[u8; 32]) -> ([u8; 32], u8) {
let mut difference = [0u8; 32];
let mut borrow = 0u8;
for (i, byte) in difference.iter_mut().enumerate() {
let (value, borrowed_a) = a[i].overflowing_sub(b[i]);
let (value, borrowed_b) = value.overflowing_sub(borrow);
*byte = value;
borrow = u8::from(borrowed_a) | u8::from(borrowed_b);
}
(difference, borrow)
}
fn select(a: &[u8; 32], b: &[u8; 32], mask: u8) -> [u8; 32] {
let mut selected = [0u8; 32];
for (i, byte) in selected.iter_mut().enumerate() {
*byte = a[i] ^ ((a[i] ^ b[i]) & mask);
}
selected
}
#[cfg(test)]
mod tests {
use super::*;
const DRAFT_GENERATOR_STRING: &str = concat!(
"0843506163653235350850617373776f72646d00000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
"0000000000000000000000000000000000000000000000000000000000000000",
"180b415f696e69746961746f720b425f726573706f6e646572107e4b4791d6a8",
"ef019b936c79fb7f2c57",
);
const DRAFT_HASH: &str = "03998087bdb1a2617bbe25ef5a7c18cd4f84f902328701790958755ee4aed1d3";
fn hex(bytes: &[u8]) -> String {
use std::fmt::Write as _;
bytes.iter().fold(String::new(), |mut text, byte| {
write!(text, "{byte:02x}").expect("writing into a String cannot fail");
text
})
}
fn draft_sid() -> [u8; 16] {
let mut sid = [0u8; 16];
sid.copy_from_slice(
&hex_decode("7e4b4791d6a8ef019b936c79fb7f2c57").expect("the vector is hex"),
);
sid
}
fn hex_decode(value: &str) -> Option<Vec<u8>> {
if value.len() % 2 != 0 {
return None;
}
(0..value.len())
.step_by(2)
.map(|i| u8::from_str_radix(&value[i..i + 2], 16).ok())
.collect()
}
#[test]
fn the_generator_string_matches_the_draft() {
let string = generator_string(b"Password", b"\x0bA_initiator\x0bB_responder", &draft_sid());
assert_eq!(
string.len(),
170,
"the draft's generator string is 170 bytes"
);
assert_eq!(hex(&string), DRAFT_GENERATOR_STRING);
}
#[test]
fn the_generator_string_hashes_to_the_draft_digest() {
let digest = Sha512::digest(generator_string(
b"Password",
b"\x0bA_initiator\x0bB_responder",
&draft_sid(),
));
assert_eq!(hex(&digest[..32]), DRAFT_HASH);
}
#[test]
fn is_all_zero_checks_every_byte() {
assert!(is_all_zero(&[0u8; 32]), "32 zero bytes are all zero");
assert!(is_all_zero(&[]), "an empty slice has no non-zero byte");
let mut leading = [0u8; 32];
leading[0] = 1;
assert!(!is_all_zero(&leading), "a non-zero first byte counts");
let mut trailing = [0u8; 32];
trailing[31] = 1;
assert!(!is_all_zero(&trailing), "a non-zero last byte counts");
}
#[test]
fn a_field_element_above_the_representative_domain_is_negated() {
let mut field = [0u8; 32];
field[0] = 1;
field[31] = 0x40;
let canonical = representative(field);
assert_eq!(
canonical[31] >> 6,
0,
"the representative has bit 254 clear"
);
assert_eq!(
representative(canonical),
canonical,
"an already canonical representative stays as it is"
);
}
}