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
//! Elligator2 for Curve25519: encode X25519 public keys as uniform bit strings.
//!
//! A raw X25519 public key is not a random string. It is the u-coordinate of a
//! curve point, and `u³ + A·u² + u` is a square for every one of them — a
//! property a censor can test with a single Legendre symbol. Any protocol that
//! puts a public key at a fixed offset in its first packet is separable from
//! random traffic on that basis alone. Elligator2 removes the tell: it maps
//! about half of all curve points to a uniformly distributed 32-byte string, and
//! maps every 32-byte string back to a point.
//!
//! ```
//! # #[cfg(feature = "keygen")] {
//! use elligator2::{from_representative, generate};
//!
//! let key = generate(&mut rand::rng()).expect("a working RNG");
//!
//! // Send this. It is indistinguishable from 32 random bytes.
//! let on_the_wire: &[u8; 32] = key.representative();
//!
//! // The peer recovers the public point, and uses *that* for Diffie-Hellman
//! // and for anything the protocol hashes.
//! assert_eq!(from_representative(on_the_wire), *key.point());
//! # }
//! ```
//!
//! # The rule
//!
//! **The representative goes on the wire. The point goes into the protocol.**
//!
//! This crate converts between the two and nothing else. It performs no
//! handshake, defines no wire format, and takes no opinion about what you hash.
//! Slotting it into an existing protocol should leave that protocol's transcript
//! byte-identical, which is what keeps interoperability testing meaningful.
//!
//! # Three traps, all of which produce working-but-broken code
//!
//! 1. **Rejection sampling.** Only about half of all curve points have an
//!    Elligator2 preimage, so key generation is a loop. Straightforward, and the
//!    only one of the three that fails loudly if you get it wrong.
//!
//! 2. **Dirty keys.** This is the one that silently produces a "uniform" encoding
//!    that is trivially distinguishable. A clamped X25519 public key always lies
//!    in the prime-order subgroup. If you only ever encode such points, an
//!    adversary decodes an observed string with the *public* map and tests
//!    whether the result has prime order: true ~1/8 of the time for genuinely
//!    random strings, and **always** for yours.
//!
//!    The fix is to publish a point drawn from the whole group:
//!    `E_pub = clamp(e)·B + T`, with `T` a uniformly chosen point of order
//!    dividing 8. The Diffie-Hellman is unaffected, and the reason is the whole
//!    trick: **every clamped X25519 scalar is a multiple of 8, and `8·T = O`**, so
//!    the peer's scalar annihilates the torsion component.
//!
//!    [`generate`] does this for you. If you build your own points, do it
//!    yourself — [`to_representative`] cannot tell, and will happily encode a
//!    clean point into a fingerprint.
//!
//!    Static, long-term keys are a different matter: they are not usually
//!    transmitted in the clear, so they have no fingerprint to fix, and dirtying
//!    one changes what the identity *is*.
//!
//! 3. **High-bit randomisation.** A representative is a field element below
//!    `(p−1)/2`, so bits 254 and 255 of the encoding are always zero. Two
//!    always-zero bits at a fixed offset is a fingerprint in its own right, and
//!    free to remove: fill them with random bits on send, mask them off on
//!    receive. [`generate`] fills them; [`from_representative`] masks them, so no
//!    caller can forget.
//!
//! # What this crate does not hide
//!
//! Packet lengths, timing, volume, and endpoint addresses. Elligator2 removes one
//! specific, decisive tell. A protocol whose packets are a constant 192 bytes and
//! arrive in a fixed pattern is still trivially fingerprinted, uniform keys or
//! not.
//!
//! # Verification
//!
//! The map is differentially tested against `curve25519-elligator2`, the Tor
//! Project's fork of `curve25519-dalek` used in the Rust obfs4/lyrebird stack, in
//! four tiers plus a test for the dirty-key property above. That crate is a
//! **dev-dependency only**. See `tests/differential.rs`, and the README for what
//! each tier pins.
//!
//! # Constant time
//!
//! The field arithmetic comes from `fiat-crypto`, machine-generated from a formal
//! specification with proofs of functional correctness and constant-time
//! behaviour. The composition on top is branch-free with respect to field values.
//!
//! One deliberate exception: [`to_representative`] returns `None` for
//! non-representable points, and [`generate`] loops until it gets a `Some`. That
//! branch is on the *discarded* candidates. The accepted key is uniform over the
//! representable set, so the retry count leaks nothing about the key finally
//! used.
//!
//! # Features
//!
//! | Feature | Default | Brings in | Gives you |
//! |---|---|---|---|
//! | — | — | `fiat-crypto`, `subtle` | [`to_representative`], [`from_representative`], [`is_montgomery_u`] |
//! | `keygen` | yes | `curve25519-dalek`, `rand_core`, `zeroize` | [`generate`], [`HiddenKey`] |
//! | `x25519` | no | `x25519-dalek` | [`HiddenKey::diffie_hellman`] |
//!
//! `no_std` throughout; no allocation anywhere.

#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs)]

#[cfg(test)]
extern crate std;

mod field;

use field::FieldElement;
use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable};

#[cfg(feature = "keygen")]
mod keygen;
#[cfg(feature = "keygen")]
pub use keygen::{HiddenKey, MAX_ATTEMPTS, generate};

/// Length of a public key, a Montgomery u-coordinate, and a representative.
/// All three are 32 bytes.
pub const LEN: usize = 32;

/// Bits 254–255 of a representative, which the map never sets.
const HIGH_BITS: u8 = 0xc0;

/// Encode a Montgomery u-coordinate as a uniform 32-byte string.
///
/// Returns `None` when the point has no preimage — roughly half the time. Callers
/// generating keys should retry with a fresh key rather than perturbing this one;
/// [`generate`] does exactly that.
///
/// `tweak` supplies the two high bits of the output, and its low bit
/// additionally selects which of the map's two branches is inverted. Both choices
/// are free parameters: any value produces a valid representative of the same
/// point. Draw it from your RNG.
///
/// # Warning
///
/// This function cannot tell a torsion-dirty point from a clean one, and encoding
/// clean points produces output that is *distinguishable from random* however
/// uniform each individual string looks. See trap 2 in the crate documentation.
#[must_use]
pub fn to_representative(point: &[u8; LEN], tweak: u8) -> Option<[u8; LEN]> {
    let u = FieldElement::from_bytes(point);

    // -2·u·(u + A). A preimage exists exactly when this is a square.
    let u_plus_a = u.add(&FieldElement::MONTGOMERY_A);
    let minus_two = FieldElement::ONE.add(&FieldElement::ONE).neg();
    let denom = u.mul(&u_plus_a).mul(&minus_two);

    let (is_sq, inv_sqrt) = FieldElement::sqrt_ratio_i(&FieldElement::ONE, &denom);

    // Branch selection: r is derived from u or from u + A.
    let base = FieldElement::conditional_select(&u, &u_plus_a, Choice::from(tweak & 1));
    let mut r = base.mul(&inv_sqrt);

    // Canonicalise the sign. The reference tests the parity of 2r, which is the
    // "is r > (p-1)/2" question expressed without a comparison.
    let double = r.add(&r);
    r.conditional_negate(double.is_negative());

    if !bool::from(is_sq) {
        return None;
    }

    let mut out = r.as_bytes();
    out[31] |= tweak & HIGH_BITS;
    Some(out)
}

/// Decode a representative back to a Montgomery u-coordinate.
///
/// Total: every 32-byte string maps to some point, which is what makes a
/// representative safe to send in the clear — an observer cannot filter on
/// "decodes to nothing", because nothing does. The two high bits are masked here
/// so no caller can forget them.
#[must_use]
pub fn from_representative(representative: &[u8; LEN]) -> [u8; LEN] {
    let mut masked = *representative;
    masked[31] &= !HIGH_BITS;
    let r = FieldElement::from_bytes(&masked);
    map_to_point(&r).as_bytes()
}

/// Whether `bytes` is a valid Curve25519 u-coordinate, i.e. whether
/// `u³ + A·u² + u` is a square.
///
/// **This is the distinguisher this crate exists to defeat**, made executable. A
/// raw X25519 public key passes every time; a uniformly random 32-byte string
/// passes about half the time. Anything emitting raw public keys at a fixed
/// offset is therefore separable from random traffic by one Legendre symbol per
/// packet.
///
/// Exposed so that a protocol's test suite can *measure* its own uniformity
/// rather than assume it. A uniformity claim with no adversary implemented
/// against it is not evidence.
#[must_use]
pub fn is_montgomery_u(bytes: &[u8; LEN]) -> bool {
    let u = FieldElement::from_bytes(bytes);
    bool::from(is_square_gx(&u))
}

/// The Elligator2 forward map on the Montgomery curve, `r ↦ u`.
///
/// ```text
/// d  = -A / (1 + 2r²)
/// gx = d³ + A·d² + d
/// u  = d           if gx is square
/// u  = -d - A      otherwise
/// ```
fn map_to_point(r: &FieldElement) -> FieldElement {
    let one = FieldElement::ONE;
    let a = FieldElement::MONTGOMERY_A;

    // Exceptional case 2r² == -1 would make the denominator zero.
    let mut tv1 = r.square2();
    tv1.conditional_assign(&FieldElement::ZERO, tv1.ct_eq_fe(&one.neg()));

    let d_1 = one.add(&tv1);
    let d = a.neg().mul(&d_1.invert());

    let gx_is_square = is_square_gx(&d);

    // `conditional_select(a, b, c)` yields `a` when `c` is 0.
    let a_temp = FieldElement::conditional_select(&a, &FieldElement::ZERO, gx_is_square);
    let mut u = d.add(&a_temp);
    u.conditional_negate(!gx_is_square);
    u
}

/// Whether `d³ + A·d² + d` is a square, i.e. whether `d` is itself the
/// u-coordinate of a curve point.
fn is_square_gx(d: &FieldElement) -> Choice {
    let inner = d
        .square()
        .add(&FieldElement::MONTGOMERY_A.mul(d))
        .add(&FieldElement::ONE);
    let gx = d.mul(&inner);
    let (is_sq, _) = FieldElement::sqrt_ratio_i(&gx, &FieldElement::ONE);
    is_sq
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The forward map is total: no 32-byte string may panic or fail.
    #[test]
    fn every_string_decodes_to_some_point() {
        use rand::Rng;
        let mut rng = rand::rng();
        for _ in 0..256 {
            let mut r = [0u8; 32];
            rng.fill_bytes(&mut r);
            let _ = from_representative(&r);
        }
        // Structured edge cases too.
        for r in [[0u8; 32], [0xff; 32], {
            let mut v = [0u8; 32];
            v[31] = 0x80;
            v
        }] {
            let _ = from_representative(&r);
        }
    }

    /// A raw X25519 public key always passes the curve-point test. This is the
    /// property the crate exists to remove, pinned so the test suite would notice
    /// if `is_montgomery_u` stopped detecting anything.
    #[cfg(feature = "keygen")]
    #[test]
    fn the_distinguisher_actually_distinguishes() {
        use curve25519_dalek::edwards::EdwardsPoint;
        use rand::Rng;

        let mut rng = rand::rng();
        let mut clean_passes = 0;
        let mut random_passes = 0;
        const TRIALS: usize = 200;

        for _ in 0..TRIALS {
            let mut sk = [0u8; 32];
            rng.fill_bytes(&mut sk);
            let point = EdwardsPoint::mul_base_clamped(sk)
                .to_montgomery()
                .to_bytes();
            if is_montgomery_u(&point) {
                clean_passes += 1;
            }

            let mut r = [0u8; 32];
            rng.fill_bytes(&mut r);
            if is_montgomery_u(&r) {
                random_passes += 1;
            }
        }

        assert_eq!(
            clean_passes, TRIALS,
            "every X25519 public key is a curve point, by construction"
        );
        let pct = random_passes * 100 / TRIALS;
        assert!(
            (30..=70).contains(&pct),
            "random strings should pass about half the time, got {pct}%"
        );
    }
}