Skip to main content

syncspin_core/pairing/
pake.rs

1//! CPace over X25519 with SHA-512, as Sendspin's code-based pairing uses it.
2//!
3//! The suite is `CPACE-X25519-SHA512` from
4//! [draft-irtf-cfrg-cpace-21](https://datatracker.ietf.org/doc/draft-irtf-cfrg-cpace/21/):
5//! group `G_X25519`, hash SHA-512, mutual confirmation flow. This module implements the
6//! primitives that flow is built from - the generator, the verified scalar multiplication, the
7//! transcript hashing, the intermediate session key and the key-confirmation tags - and pins them
8//! to the draft's vectors in `tests/pake_vectors.rs`. The message flow itself belongs to the
9//! session layer, which knows when a share or a tag crosses the wire.
10//!
11//! # What the generator is
12//!
13//! `generator_string` is `lv_cat(DSI, PRS, zero_bytes(len_zpad), CI, sid)` with the zero padding
14//! sized so that the first SHA-512 block holds exactly the encoded `DSI` and `PRS` (§8.1,
15//! Appendix A.2). The first 32 bytes of its SHA-512 digest are decoded as a u-coordinate
16//! (`decodeUCoordinate(_, 255)` from [RFC 7748]) and mapped with Elligator 2. The associated
17//! data `ADa`/`ADb` is *not* an input: it enters the transcript that the confirmation flow
18//! hashes, not the generator.
19//!
20//! # The transcript and the key confirmation
21//!
22//! Sendspin fixes CPace's initiator-responder mode, so the transcript is
23//! [`transcript_ir`]: `lv_cat(Ya, ADa) || lv_cat(Yb, ADb)`. [`intermediate_session_key`] hashes
24//! `lv_cat(G.DSI_ISK, sid, K)` followed by that transcript. The explicit key confirmation of
25//! §10.4 derives `mac_key = H(b"CPaceMac" || sid || ISK)` and authenticates the sender's own
26//! `lv_cat(share, associated data)` with HMAC-SHA-512, which is [`key_confirmation_tag`].
27//! [`transcript_oc`] is the parallel-execution form: Sendspin does not use it, but the draft's
28//! vectors cover it and keeping it proves the two forms differ only in the ordering step.
29//!
30//! # Representative convention
31//!
32//! CPace hands the map an arbitrary field element. `elligator2::from_representative` instead
33//! expects a representative, a value below `(p-1)/2`, and masks bits 254 and 255 of its input.
34//! The draft's field element can have bit 254 set, and then passing it straight in changes the
35//! point: for the §B.1.1 vector the raw call returns `97ef2dc8...cd72fe23` instead of the
36//! draft's `d04bf6d4...2f05a73f`. `representative` closes the gap exactly: Elligator 2 uses
37//! only `r^2`, so `r` and `-r` map to the same point, and negating a value with bit 254 set
38//! yields one the crate accepts. The §B.1.1 generator matches only with that normalisation.
39//!
40//! # Secret handling
41//!
42//! `PRS`, the scalar, the shared point, `ISK` and the tags derive from the pairing code or from a
43//! scalar. This module returns them as bytes, exactly as [`mod@super::wrap`] does, and never
44//! formats them: no `Debug`, no `Display`, no error string carries a value. [`key_confirmation_tag`]
45//! and [`verify_key_confirmation_tag`] are branch-free over the secret-derived tag.
46//!
47//! # Not reviewed
48//!
49//! Neither this module nor `elligator2` 0.1 has had an external cryptographic review. The
50//! draft vectors pin the arithmetic, not the review.
51
52use anyhow::{bail, Result};
53use hmac::{Hmac, Mac};
54use sha2::{Digest, Sha512};
55
56/// `G_X25519.DSI`, the group's domain-separation identifier (§8.2).
57const DSI: &[u8] = b"CPace255";
58
59/// `G.DSI_ISK`, the domain-separation identifier of the ISK (§7.2).
60const DSI_ISK: &[u8] = b"CPace255_ISK";
61
62/// The label that prefixes the MCF MAC key (§10.4).
63const MAC_LABEL: &[u8] = b"CPaceMac";
64
65/// The input block size of SHA-512 in bytes (`H.s_in_bytes`), which `generator_string` pads to.
66const SHA512_BLOCK_LEN: usize = 128;
67
68/// Length of a CPace public share in bytes.
69pub const SHARE_LEN: usize = 32;
70
71/// Length of the intermediate session key in bytes: one SHA-512 output.
72pub const ISK_LEN: usize = 64;
73
74/// Length of a key-confirmation tag in bytes: one HMAC-SHA-512 output.
75pub const TAG_LEN: usize = 64;
76
77/// The field modulus `p = 2^255 - 19`, little-endian.
78const FIELD_MODULUS: [u8; 32] = [
79    0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
80    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f,
81];
82
83/// Derives the CPace generator for this `PRS`, `CI` and `sid`.
84///
85/// Returns the generator's u-coordinate as 32 little-endian bytes, the encoding every group
86/// element in CPace uses. `PRS` is the pairing code's bytes, `CI` the channel identifier (empty
87/// when the parties are identified by their associated data instead) and `sid` the session id.
88///
89/// The function is total: every input hashes to a field element, and Elligator 2 maps every
90/// field element to a curve point.
91///
92/// # Example
93///
94/// ```
95/// use syncspin_core::pairing::pake::generator;
96///
97/// // Draft §B.1.1, X25519 with SHA-512.
98/// let sid = [
99///     0x7e, 0x4b, 0x47, 0x91, 0xd6, 0xa8, 0xef, 0x01, 0x9b, 0x93, 0x6c, 0x79, 0xfb, 0x7f,
100///     0x2c, 0x57,
101/// ];
102/// let g = generator(b"Password", b"\x0bA_initiator\x0bB_responder", &sid);
103/// assert_eq!(
104///     g,
105///     [
106///         0xd0, 0x4b, 0xf6, 0xd4, 0x1f, 0x6a, 0x28, 0x96, 0x32, 0xa2, 0xe9, 0x29, 0xfa, 0x29,
107///         0xbe, 0xbd, 0x51, 0x09, 0x25, 0x12, 0xa7, 0x82, 0x9f, 0xdd, 0xe7, 0xd3, 0x14, 0xb6,
108///         0x2f, 0x05, 0xa7, 0x3f,
109///     ]
110/// );
111/// ```
112pub fn generator(prs: &[u8], ci: &[u8], sid: &[u8]) -> [u8; 32] {
113    let digest = Sha512::digest(generator_string(prs, ci, sid));
114
115    // `decodeUCoordinate(gen_str_hash, G.field_size_bits)`: the top 32 bytes of the digest
116    // with bit 255 ignored.
117    let mut field = [0u8; 32];
118    field.copy_from_slice(&digest[..32]);
119    field[31] &= 0x7f;
120
121    elligator2::from_representative(&representative(field))
122}
123
124/// Computes `G_X25519.scalar_mult_vfy(scalar, u)`, the verified scalar multiplication.
125///
126/// X25519 clamps the scalar and ignores bit 255 of `u`, exactly as [RFC 7748] specifies, so the
127/// non-canonical encodings of draft §B.1.10 are handled without a separate branch. A result that
128/// is the neutral element means `u` was a low-order point; that is the abort case the draft
129/// requires and the error this function returns.
130///
131/// # Errors
132///
133/// Fails when `u` encodes a low-order point, that is when the shared point is the neutral
134/// element. CPace requires the caller to abort the round in that case.
135pub fn scalar_mult_vfy(scalar: &[u8; 32], u: &[u8; 32]) -> Result<[u8; 32]> {
136    let point = x25519_dalek::x25519(*scalar, *u);
137    // Fold rather than compare: a slice comparison can stop at the first differing byte, which
138    // would make the timing depend on how many leading bytes of a valid point are zero.
139    if is_all_zero(&point) {
140        bail!("the peer's CPace share encodes a low-order point");
141    }
142    Ok(point)
143}
144
145/// Returns whether every byte is zero, touching the whole slice.
146fn is_all_zero(bytes: &[u8]) -> bool {
147    bytes.iter().fold(0u8, |acc, &byte| acc | byte) == 0
148}
149
150/// Computes a public share `Y = G.scalar_mult(scalar, generator)`.
151///
152/// X25519 clamps the scalar, exactly as `G_X25519.sample_scalar` does, so a scalar drawn from the
153/// CSPRNG is used here unchanged. The generator is public, so the low-order check costs nothing
154/// secret and rejects a degenerate generator instead of returning the neutral element.
155///
156/// # Errors
157///
158/// Fails when the group operation yields the neutral element, which only a low-order `generator`
159/// can cause.
160pub fn public_share(scalar: &[u8; 32], generator: &[u8; 32]) -> Result<[u8; 32]> {
161    scalar_mult_vfy(scalar, generator)
162}
163
164/// Concatenates each part with its LEB128 length prepended (`lv_cat` from §6.3).
165///
166/// The length makes the encoding prefix-free, which is what lets the transcript be hashed without
167/// an ambiguity between a share and the associated data that follows it.
168///
169/// # Example
170///
171/// ```
172/// use syncspin_core::pairing::pake::lv_cat;
173///
174/// // Draft §A.1.4.
175/// assert_eq!(
176///     lv_cat(&[b"1234".as_slice(), b"5", b"", b"678"]),
177///     [
178///         0x04, b'1', b'2', b'3', b'4', 0x01, b'5', 0x00, 0x03, b'6', b'7', b'8',
179///     ]
180/// );
181/// ```
182pub fn lv_cat(parts: &[&[u8]]) -> Vec<u8> {
183    let mut joined = Vec::new();
184    for part in parts {
185        push_lv(&mut joined, part);
186    }
187    joined
188}
189
190/// Builds the initiator-responder transcript `lv_cat(Ya, ADa) || lv_cat(Yb, ADb)` (§6.3).
191///
192/// Both sides hash the same ordering: the initiator's share and associated data first, then the
193/// responder's, whichever party computes it. Sendspin's `ADa` is `b"server"` and its `ADb` is
194/// `b"client"`.
195pub fn transcript_ir(ya: &[u8], ad_a: &[u8], yb: &[u8], ad_b: &[u8]) -> Vec<u8> {
196    let mut transcript = lv_cat(&[ya, ad_a]);
197    transcript.extend_from_slice(&lv_cat(&[yb, ad_b]));
198    transcript
199}
200
201/// Builds the parallel-execution transcript `o_cat(lv_cat(Ya, ADa), lv_cat(Yb, ADb))` (§6.3).
202///
203/// The two messages are ordered lexicographically and prefixed with `b"oc"`, so neither party has
204/// to know who spoke first. Sendspin fixes an initiator and a responder, so it uses
205/// [`transcript_ir`]; this form exists because the draft's vectors cover it.
206pub fn transcript_oc(ya: &[u8], ad_a: &[u8], yb: &[u8], ad_b: &[u8]) -> Vec<u8> {
207    let initiator = lv_cat(&[ya, ad_a]);
208    let responder = lv_cat(&[yb, ad_b]);
209    let mut transcript = Vec::from(b"oc".as_slice());
210    if lexicographically_larger(&initiator, &responder) {
211        transcript.extend_from_slice(&initiator);
212        transcript.extend_from_slice(&responder);
213    } else {
214        transcript.extend_from_slice(&responder);
215        transcript.extend_from_slice(&initiator);
216    }
217    transcript
218}
219
220/// Derives `ISK = H(lv_cat(G.DSI_ISK, sid, K) || transcript)` (§7.2).
221///
222/// `shared_point` is the secret point `K = scalar_mult_vfy(scalar, peer_share)`, and `transcript`
223/// is [`transcript_ir`] or [`transcript_oc`]. The result is the 64-byte intermediate session key,
224/// which the higher-level protocol processes before use: Sendspin derives `K_wrap` from it with
225/// [`super::wrap::k_wrap`].
226///
227/// The value is secret. It is returned as bytes and never formatted.
228pub fn intermediate_session_key(
229    sid: &[u8],
230    shared_point: &[u8],
231    transcript: &[u8],
232) -> [u8; ISK_LEN] {
233    let mut input = lv_cat(&[DSI_ISK, sid, shared_point]);
234    input.extend_from_slice(transcript);
235    Sha512::digest(input).into()
236}
237
238/// Computes the explicit key-confirmation tag of the sender's own message (§10.4).
239///
240/// `mac_key = H(b"CPaceMac" || sid || ISK)`, raw and without length prefixes, then
241/// `T = HMAC-SHA-512(mac_key, lv_cat(share, associated data))`. Passing the initiator's `Ya` and
242/// `ADa` yields `Ta` (`server_kc`); the responder's `Yb` and `ADb` yield `Tb` (`client_kc`).
243///
244/// The tag is secret-derived. It is returned as bytes and never formatted.
245pub fn key_confirmation_tag(
246    sid: &[u8],
247    isk: &[u8; ISK_LEN],
248    share: &[u8],
249    ad: &[u8],
250) -> [u8; TAG_LEN] {
251    let mut key_input = Vec::from(MAC_LABEL);
252    key_input.extend_from_slice(sid);
253    key_input.extend_from_slice(isk);
254    let mac_key = Sha512::digest(key_input);
255
256    let mut mac = <Hmac<Sha512> as Mac>::new_from_slice(&mac_key)
257        .expect("HMAC-SHA-512 accepts a key of any length");
258    mac.update(&lv_cat(&[share, ad]));
259    mac.finalize().into_bytes().into()
260}
261
262/// Returns whether a received tag equals the one this side derived.
263///
264/// The comparison touches every byte of both tags and folds the differences into one value, so it
265/// does not stop at the first mismatch: the tags are derived from `ISK`, and an early exit would
266/// leak how many leading bytes an attacker guessed. Only the single final result depends on the
267/// data, and that result is public - it decides whether the round continues.
268#[must_use]
269pub fn verify_key_confirmation_tag(expected: &[u8; TAG_LEN], received: &[u8; TAG_LEN]) -> bool {
270    let difference = expected
271        .iter()
272        .zip(received)
273        .fold(0u8, |acc, (a, b)| acc | (a ^ b));
274    difference == 0
275}
276
277/// Returns whether `left` is greater than `right` in the draft's lexicographical order (§A.3.1).
278fn lexicographically_larger(left: &[u8], right: &[u8]) -> bool {
279    for (a, b) in left.iter().zip(right) {
280        if a > b {
281            return true;
282        }
283        if a < b {
284            return false;
285        }
286    }
287    left.len() > right.len()
288}
289
290/// Builds `generator_string(DSI, PRS, CI, sid, H.s_in_bytes)` (§8.1, Appendix A.2).
291fn generator_string(prs: &[u8], ci: &[u8], sid: &[u8]) -> Vec<u8> {
292    // The pad fills the first hash block after the encoded DSI and PRS, leaving room for the
293    // length byte of the pad field itself.
294    let pad = SHA512_BLOCK_LEN.saturating_sub(
295        1 + prepend_len_len(DSI.len()) + DSI.len() + prepend_len_len(prs.len()) + prs.len(),
296    );
297
298    let mut string = Vec::new();
299    push_lv(&mut string, DSI);
300    push_lv(&mut string, prs);
301    push_len(&mut string, pad);
302    string.resize(string.len() + pad, 0);
303    push_lv(&mut string, ci);
304    push_lv(&mut string, sid);
305    string
306}
307
308/// Appends `prepend_len(bytes)`: the LEB128 length followed by the bytes.
309fn push_lv(out: &mut Vec<u8>, bytes: &[u8]) {
310    push_len(out, bytes.len());
311    out.extend_from_slice(bytes);
312}
313
314/// Appends `len` as an unsigned LEB128 integer.
315fn push_len(out: &mut Vec<u8>, mut len: usize) {
316    loop {
317        let byte = (len & 0x7f) as u8;
318        len >>= 7;
319        if len == 0 {
320            out.push(byte);
321            return;
322        }
323        out.push(byte | 0x80);
324    }
325}
326
327/// Returns how many bytes `prepend_len` uses for a value of `len` bytes.
328fn prepend_len_len(len: usize) -> usize {
329    let mut len = len;
330    let mut width = 1;
331    while len >= 0x80 {
332        len >>= 7;
333        width += 1;
334    }
335    width
336}
337
338/// Maps a field element into the representative domain `elligator2` accepts.
339///
340/// The crate's representatives are below `(p-1)/2` and it masks bits 254 and 255 of whatever it
341/// is given. CPace's field element can have bit 254 set, so it is reduced modulo `p` and, when
342/// bit 254 is still set, replaced by its negation. That is exact: Elligator 2 uses only `r^2`,
343/// so `r` and `-r` map to the same point.
344///
345/// Both selections are branch-free. The inputs are derived from the pairing code, which is a
346/// secret, and a data-dependent branch here would leak a bit of the hash output.
347fn representative(field: [u8; 32]) -> [u8; 32] {
348    // `field` is below 2^255 and therefore below 2p, so one subtraction reduces it.
349    let (reduced, borrow) = subtract(&field, &FIELD_MODULUS);
350    let reduced = select(&field, &reduced, borrow.wrapping_sub(1));
351
352    let (negated, _) = subtract(&FIELD_MODULUS, &reduced);
353    select(&reduced, &negated, 0u8.wrapping_sub(reduced[31] >> 6))
354}
355
356/// Subtracts two little-endian 256-bit integers, returning the difference and the borrow.
357fn subtract(a: &[u8; 32], b: &[u8; 32]) -> ([u8; 32], u8) {
358    let mut difference = [0u8; 32];
359    let mut borrow = 0u8;
360    for (i, byte) in difference.iter_mut().enumerate() {
361        let (value, borrowed_a) = a[i].overflowing_sub(b[i]);
362        let (value, borrowed_b) = value.overflowing_sub(borrow);
363        *byte = value;
364        borrow = u8::from(borrowed_a) | u8::from(borrowed_b);
365    }
366    (difference, borrow)
367}
368
369/// Returns `b` when `mask` is all ones and `a` when it is zero, without branching.
370fn select(a: &[u8; 32], b: &[u8; 32], mask: u8) -> [u8; 32] {
371    let mut selected = [0u8; 32];
372    for (i, byte) in selected.iter_mut().enumerate() {
373        *byte = a[i] ^ ((a[i] ^ b[i]) & mask);
374    }
375    selected
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381
382    /// The draft's §B.1.1 `generator_string`, 170 bytes.
383    const DRAFT_GENERATOR_STRING: &str = concat!(
384        "0843506163653235350850617373776f72646d00000000000000000000000000",
385        "0000000000000000000000000000000000000000000000000000000000000000",
386        "0000000000000000000000000000000000000000000000000000000000000000",
387        "0000000000000000000000000000000000000000000000000000000000000000",
388        "180b415f696e69746961746f720b425f726573706f6e646572107e4b4791d6a8",
389        "ef019b936c79fb7f2c57",
390    );
391
392    /// The draft's §B.1.1 SHA-512 digest of that string, first 32 bytes.
393    const DRAFT_HASH: &str = "03998087bdb1a2617bbe25ef5a7c18cd4f84f902328701790958755ee4aed1d3";
394
395    fn hex(bytes: &[u8]) -> String {
396        use std::fmt::Write as _;
397        bytes.iter().fold(String::new(), |mut text, byte| {
398            write!(text, "{byte:02x}").expect("writing into a String cannot fail");
399            text
400        })
401    }
402
403    fn draft_sid() -> [u8; 16] {
404        let mut sid = [0u8; 16];
405        sid.copy_from_slice(
406            &hex_decode("7e4b4791d6a8ef019b936c79fb7f2c57").expect("the vector is hex"),
407        );
408        sid
409    }
410
411    fn hex_decode(value: &str) -> Option<Vec<u8>> {
412        if value.len() % 2 != 0 {
413            return None;
414        }
415        (0..value.len())
416            .step_by(2)
417            .map(|i| u8::from_str_radix(&value[i..i + 2], 16).ok())
418            .collect()
419    }
420
421    #[test]
422    fn the_generator_string_matches_the_draft() {
423        let string = generator_string(b"Password", b"\x0bA_initiator\x0bB_responder", &draft_sid());
424        assert_eq!(
425            string.len(),
426            170,
427            "the draft's generator string is 170 bytes"
428        );
429        assert_eq!(hex(&string), DRAFT_GENERATOR_STRING);
430    }
431
432    #[test]
433    fn the_generator_string_hashes_to_the_draft_digest() {
434        let digest = Sha512::digest(generator_string(
435            b"Password",
436            b"\x0bA_initiator\x0bB_responder",
437            &draft_sid(),
438        ));
439        assert_eq!(hex(&digest[..32]), DRAFT_HASH);
440    }
441
442    #[test]
443    fn is_all_zero_checks_every_byte() {
444        assert!(is_all_zero(&[0u8; 32]), "32 zero bytes are all zero");
445        assert!(is_all_zero(&[]), "an empty slice has no non-zero byte");
446
447        let mut leading = [0u8; 32];
448        leading[0] = 1;
449        assert!(!is_all_zero(&leading), "a non-zero first byte counts");
450
451        let mut trailing = [0u8; 32];
452        trailing[31] = 1;
453        assert!(!is_all_zero(&trailing), "a non-zero last byte counts");
454    }
455
456    #[test]
457    fn a_field_element_above_the_representative_domain_is_negated() {
458        // 2^254 + 1: bit 254 set, which `from_representative` would mask away. Negating it
459        // gives a value the map reads unchanged, and the map is even, so both agree.
460        let mut field = [0u8; 32];
461        field[0] = 1;
462        field[31] = 0x40;
463
464        let canonical = representative(field);
465        assert_eq!(
466            canonical[31] >> 6,
467            0,
468            "the representative has bit 254 clear"
469        );
470        assert_eq!(
471            representative(canonical),
472            canonical,
473            "an already canonical representative stays as it is"
474        );
475    }
476}