elligator2 0.1.0

Elligator2 for Curve25519: encode X25519 public keys as uniform random bit strings and back. Built on fiat-crypto's formally verified field arithmetic, differentially tested, no_std.
Documentation
//! Generation of keypairs that are both torsion-dirty and representable.
//!
//! Split from the encoding functions because it is the opinionated half. The map
//! is a fact about Curve25519; the choices here — which torsion point, where the
//! tweak comes from, how many retries — are conventions. They match what the
//! obfs4 stack does, but a protocol with its own key-derivation scheme should
//! feel free to build its points itself and call [`to_representative`] directly.
//!
//! [`to_representative`]: crate::to_representative

use curve25519_dalek::constants::EIGHT_TORSION;
use curve25519_dalek::edwards::EdwardsPoint;
use rand_core::CryptoRng;
use zeroize::ZeroizeOnDrop;

use crate::{LEN, to_representative};

/// Cap on generate-and-retry attempts.
///
/// Each attempt succeeds with probability ≈ 1/2, so 64 failures in a row has
/// probability 2⁻⁶⁴. Reaching the cap means the RNG is broken, not that you were
/// unlucky, and [`generate`] returning `None` is the correct response to that.
pub const MAX_ATTEMPTS: usize = 64;

/// A keypair whose public key can be sent as a uniform bit string.
///
/// The secret is zeroized on drop. The point and the representative are public
/// values and are not.
#[derive(ZeroizeOnDrop)]
pub struct HiddenKey {
    /// The unclamped secret seed. Clamping happens at use, as for any X25519 key.
    secret: [u8; LEN],
    /// Canonical Montgomery u-coordinate of the **dirty** public point.
    ///
    /// This is the value to feed into Diffie-Hellman and into anything the
    /// protocol hashes. A peer decoding the representative lands on exactly these
    /// bytes.
    #[zeroize(skip)]
    point: [u8; LEN],
    /// Uniform wire encoding, high bits already randomised.
    #[zeroize(skip)]
    representative: [u8; LEN],
}

impl HiddenKey {
    /// The public point, as a Montgomery u-coordinate. **This** is what goes into
    /// the protocol.
    #[must_use]
    pub const fn point(&self) -> &[u8; LEN] {
        &self.point
    }

    /// The uniform encoding of [`point`](Self::point). **This** is what goes on
    /// the wire.
    #[must_use]
    pub const fn representative(&self) -> &[u8; LEN] {
        &self.representative
    }

    /// The raw secret scalar, unclamped, for feeding to your own X25519.
    ///
    /// With the `x25519` feature you can use [`diffie_hellman`] instead and skip
    /// handling this at all.
    ///
    /// [`diffie_hellman`]: Self::diffie_hellman
    #[must_use]
    pub const fn secret_bytes(&self) -> &[u8; LEN] {
        &self.secret
    }

    /// The secret as an `x25519-dalek` [`StaticSecret`], for handing to code that
    /// wants to drive the key exchange itself.
    ///
    /// [`StaticSecret`]: x25519_dalek::StaticSecret
    #[cfg(feature = "x25519")]
    #[must_use]
    pub fn static_secret(&self) -> x25519_dalek::StaticSecret {
        x25519_dalek::StaticSecret::from(self.secret)
    }

    /// Diffie-Hellman against a peer's public key.
    ///
    /// Clamping happens inside `x25519-dalek`, exactly as for any other X25519
    /// operation — the dirtiness lives in the *published point*, never in the
    /// scalar arithmetic, which is precisely why the shared secret is unaffected
    /// by it.
    #[cfg(feature = "x25519")]
    #[must_use]
    pub fn diffie_hellman(&self, peer: &x25519_dalek::PublicKey) -> x25519_dalek::SharedSecret {
        self.static_secret().diffie_hellman(peer)
    }
}

impl core::fmt::Debug for HiddenKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        // The secret must never reach a log line, so it is not in the output and
        // the struct is marked non-exhaustive to say so.
        f.debug_struct("HiddenKey")
            .field("point", &Hex4(&self.point))
            .field("representative", &Hex4(&self.representative))
            .finish_non_exhaustive()
    }
}

struct Hex4<'a>(&'a [u8; LEN]);

impl core::fmt::Debug for Hex4<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        for byte in &self.0[..4] {
            write!(f, "{byte:02x}")?;
        }
        f.write_str("…")
    }
}

/// Generate a keypair whose public point is torsion-dirty **and**
/// Elligator2-representable.
///
/// Loops until both hold; see [`MAX_ATTEMPTS`]. Returns `None` only if the cap is
/// reached, which with a working RNG has probability 2⁻⁶⁴ — treat it as a broken
/// RNG rather than as a retryable condition.
///
/// The number of iterations depends on the discarded candidates, not on the
/// accepted key, and the accepted key is uniform over the representable set, so
/// the retry count leaks nothing about the secret finally used.
///
/// Both the torsion point and the representative's high bits are drawn from
/// `rng`. See traps 2 and 3 in the crate documentation for why both matter.
#[must_use]
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Option<HiddenKey> {
    for _ in 0..MAX_ATTEMPTS {
        let mut sk = [0u8; LEN];
        rng.fill_bytes(&mut sk);

        // Two of the RNG's bytes do double duty, and neither weakens the key:
        //  - `sk[0]`'s low 3 bits are cleared by clamping, so they are free; they
        //    choose the torsion point, giving a uniform coset.
        //  - `tweak` fills the representative's two unused high bits and picks
        //    the encoder branch.
        let torsion = EIGHT_TORSION[usize::from(sk[0] & 7)];
        let mut tweak = [0u8; 1];
        rng.fill_bytes(&mut tweak);

        let dirty: EdwardsPoint = EdwardsPoint::mul_base_clamped(sk) + torsion;
        let point = dirty.to_montgomery().to_bytes();

        if let Some(representative) = to_representative(&point, tweak[0]) {
            return Some(HiddenKey {
                secret: sk,
                point,
                representative,
            });
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::from_representative;
    use rand::Rng;

    #[test]
    fn generation_succeeds_and_round_trips() {
        let mut rng = rand::rng();
        for _ in 0..64 {
            let e = generate(&mut rng).expect("generate");
            assert_eq!(
                from_representative(e.representative()),
                *e.point(),
                "decoding a representative must recover the exact point that was encoded"
            );
        }
    }

    /// The property that makes the whole exercise worthwhile: the two unused
    /// high bits must not be constant.
    #[test]
    fn high_bits_are_randomised() {
        let mut rng = rand::rng();
        let mut seen = [false; 4];
        for _ in 0..256 {
            let e = generate(&mut rng).expect("generate");
            seen[usize::from(e.representative()[31] >> 6)] = true;
        }
        assert!(
            seen.iter().all(|s| *s),
            "all four values of the top two bits must occur: {seen:?}"
        );
    }

    /// Decoding must ignore the high bits, or a randomised representative would
    /// decode to the wrong point.
    #[test]
    fn decoding_ignores_the_high_bits() {
        let mut rng = rand::rng();
        let e = generate(&mut rng).expect("generate");
        let mut alt = *e.representative();
        alt[31] ^= 0xc0;
        assert_eq!(
            from_representative(&alt),
            from_representative(e.representative())
        );
    }

    /// Roughly half of all points are representable. A rate far from 50% means
    /// the encodability test is wrong.
    #[test]
    fn about_half_of_candidates_are_representable() {
        let mut rng = rand::rng();
        let mut representable = 0;
        const TRIALS: usize = 512;
        for _ in 0..TRIALS {
            let mut sk = [0u8; 32];
            rng.fill_bytes(&mut sk);
            let torsion = EIGHT_TORSION[usize::from(sk[0] & 7)];
            let point = (EdwardsPoint::mul_base_clamped(sk) + torsion)
                .to_montgomery()
                .to_bytes();
            if to_representative(&point, 0).is_some() {
                representable += 1;
            }
        }
        let pct = representable * 100 / TRIALS;
        assert!(
            (35..=65).contains(&pct),
            "representable rate {pct}% is implausibly far from 50%"
        );
    }

    /// The secret must not leak through a log line.
    #[test]
    fn debug_does_not_print_the_secret() {
        use std::format;
        let e = generate(&mut rand::rng()).expect("generate");
        let rendered = format!("{e:?}");
        let secret_hex: std::string::String = e
            .secret_bytes()
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        assert!(
            !rendered.contains(&secret_hex[..8]),
            "Debug leaked secret material: {rendered}"
        );
    }

    /// The shared secret must be unaffected by the torsion component. This is the
    /// claim that makes dirty keys safe, and it is worth checking rather than
    /// believing: `8·T = O` and every clamped scalar is a multiple of 8, so the
    /// peer's scalar annihilates `T`.
    #[cfg(feature = "x25519")]
    #[test]
    fn torsion_does_not_disturb_the_shared_secret() {
        use x25519_dalek::{PublicKey, StaticSecret};

        let mut rng = rand::rng();
        for _ in 0..32 {
            let hidden = generate(&mut rng).expect("generate");

            let mut peer_sk = [0u8; 32];
            rng.fill_bytes(&mut peer_sk);
            let peer = StaticSecret::from(peer_sk);

            // Us, dirty point and all, against the peer's public key.
            let ours = hidden.diffie_hellman(&PublicKey::from(&peer));

            // The peer, against the dirty point we published.
            let theirs = peer.diffie_hellman(&PublicKey::from(*hidden.point()));

            assert_eq!(
                ours.as_bytes(),
                theirs.as_bytes(),
                "the torsion component must be annihilated by the peer's clamped scalar"
            );
        }
    }
}