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
//! GF(2²⁵⁵ − 19) arithmetic for the Elligator2 map.
//!
//! # Why this exists at all
//!
//! `curve25519-dalek` keeps `FieldElement` `pub(crate)`, so there is no public
//! square root, inversion, or Legendre symbol in the mainline curve stack.
//! Elligator2 needs all three. The options were to fork a curve library or to
//! build a thin layer over verified field arithmetic; this is the latter.
//!
//! # Why `fiat-crypto`
//!
//! The limb-level arithmetic here is **not** hand-written. It comes from
//! `fiat-crypto`, whose curve25519 backend is machine-generated from a formal
//! specification and carries a proof of functional correctness and of
//! constant-time behaviour. It is also already in the dependency graph of any
//! project using `curve25519-dalek` 5.x, so depending on it directly usually adds
//! zero new code to the build.
//!
//! What is hand-written is only the composition: exponentiation chains, the
//! square-root-of-a-ratio trick, and canonical encoding. Those are the parts the
//! differential tests against `curve25519-elligator2` exercise.
//!
//! # Constant time
//!
//! Every operation here is branch-free with respect to field values. Selection
//! and negation go through `subtle::Choice`; there is no `if` on a field element
//! anywhere in this file. `fiat_25519_selectznz` is the verified primitive
//! underneath [`FieldElement::conditional_select`].

/// Subtraction is used only by this module's own tests — the map itself never
/// needs it, since every difference it takes is already expressed as `add(neg)`.
#[cfg(test)]
use fiat_crypto::curve25519_64::fiat_25519_sub;
use fiat_crypto::curve25519_64::{
    fiat_25519_add, fiat_25519_carry, fiat_25519_carry_mul, fiat_25519_carry_square,
    fiat_25519_from_bytes, fiat_25519_loose_field_element, fiat_25519_opp, fiat_25519_relax,
    fiat_25519_selectznz, fiat_25519_tight_field_element, fiat_25519_to_bytes,
};
use subtle::{Choice, ConditionallyNegatable, ConditionallySelectable, ConstantTimeEq};

/// An element of GF(2²⁵⁵ − 19), held in fiat-crypto's tight 5×51-bit form.
#[derive(Clone, Copy)]
pub(crate) struct FieldElement(fiat_25519_tight_field_element);

/// Hand-written because fiat-crypto's generated types derive nothing, and
/// because the canonical encoding is the only representation worth printing —
/// raw limbs are not comparable between equal values.
impl core::fmt::Debug for FieldElement {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("FieldElement(")?;
        for byte in self.as_bytes() {
            write!(f, "{byte:02x}")?;
        }
        f.write_str(")")
    }
}

impl FieldElement {
    pub(crate) const ZERO: Self = Self(fiat_25519_tight_field_element([0, 0, 0, 0, 0]));
    pub(crate) const ONE: Self = Self(fiat_25519_tight_field_element([1, 0, 0, 0, 0]));

    /// The Montgomery curve constant `A = 486662`.
    pub(crate) const MONTGOMERY_A: Self =
        Self(fiat_25519_tight_field_element([486_662, 0, 0, 0, 0]));

    /// Decode 32 little-endian bytes.
    ///
    /// The high bit is masked off, matching every Curve25519 implementation:
    /// field elements are 255 bits and the 256th is not part of the value.
    pub(crate) fn from_bytes(bytes: &[u8; 32]) -> Self {
        let mut masked = *bytes;
        masked[31] &= 0x7f;
        let mut out = fiat_25519_tight_field_element([0; 5]);
        fiat_25519_from_bytes(&mut out, &masked);
        Self(out)
    }

    /// Encode canonically: the unique representative in `[0, p)`.
    pub(crate) fn as_bytes(&self) -> [u8; 32] {
        let mut out = [0u8; 32];
        fiat_25519_to_bytes(&mut out, &self.0);
        out
    }

    fn relax(&self) -> fiat_25519_loose_field_element {
        let mut out = fiat_25519_loose_field_element([0; 5]);
        fiat_25519_relax(&mut out, &self.0);
        out
    }

    fn from_loose(loose: &fiat_25519_loose_field_element) -> Self {
        let mut out = fiat_25519_tight_field_element([0; 5]);
        fiat_25519_carry(&mut out, loose);
        Self(out)
    }

    pub(crate) fn add(&self, rhs: &Self) -> Self {
        let mut out = fiat_25519_loose_field_element([0; 5]);
        fiat_25519_add(&mut out, &self.0, &rhs.0);
        Self::from_loose(&out)
    }

    #[cfg(test)]
    pub(crate) fn sub(&self, rhs: &Self) -> Self {
        let mut out = fiat_25519_loose_field_element([0; 5]);
        fiat_25519_sub(&mut out, &self.0, &rhs.0);
        Self::from_loose(&out)
    }

    pub(crate) fn neg(&self) -> Self {
        let mut out = fiat_25519_loose_field_element([0; 5]);
        fiat_25519_opp(&mut out, &self.0);
        Self::from_loose(&out)
    }

    pub(crate) fn mul(&self, rhs: &Self) -> Self {
        let mut out = fiat_25519_tight_field_element([0; 5]);
        fiat_25519_carry_mul(&mut out, &self.relax(), &rhs.relax());
        Self(out)
    }

    pub(crate) fn square(&self) -> Self {
        let mut out = fiat_25519_tight_field_element([0; 5]);
        fiat_25519_carry_square(&mut out, &self.relax());
        Self(out)
    }

    /// `2·self²`. Named after the dalek helper the reference map uses.
    pub(crate) fn square2(&self) -> Self {
        let sq = self.square();
        sq.add(&sq)
    }

    /// Repeated squaring: `self^(2^k)`.
    pub(crate) fn pow2k(&self, k: u32) -> Self {
        let mut acc = *self;
        for _ in 0..k {
            acc = acc.square();
        }
        acc
    }

    /// `self^(2^250 − 1)`, the shared prefix of the inversion and square-root
    /// exponentiation chains.
    ///
    /// The addition chain is the standard one; each temporary's exponent is
    /// annotated so the chain can be checked by hand rather than trusted.
    fn pow22501(&self) -> (Self, Self) {
        let t0 = self.square(); // 2^1
        let t1 = t0.square().square(); // 2^3
        let t2 = self.mul(&t1); // 2^3 + 2^0
        let t3 = t0.mul(&t2); // 3,1,0
        let t4 = t3.square(); // 4,2,1
        let t5 = t2.mul(&t4); // 4,3,2,1,0
        let t6 = t5.pow2k(5); // 9..5
        let t7 = t6.mul(&t5); // 9..0
        let t8 = t7.pow2k(10); // 19..10
        let t9 = t8.mul(&t7); // 19..0
        let t10 = t9.pow2k(20); // 39..20
        let t11 = t10.mul(&t9); // 39..0
        let t12 = t11.pow2k(10); // 49..10
        let t13 = t12.mul(&t7); // 49..0
        let t14 = t13.pow2k(50); // 99..50
        let t15 = t14.mul(&t13); // 99..0
        let t16 = t15.pow2k(100); // 199..100
        let t17 = t16.mul(&t15); // 199..0
        let t18 = t17.pow2k(50); // 249..50
        let t19 = t18.mul(&t13); // 249..0
        (t19, t3)
    }

    /// `self^((p−5)/8)`, whose exponent bits are `101111…11`.
    pub(crate) fn pow_p58(&self) -> Self {
        let (t19, _) = self.pow22501();
        t19.pow2k(2).mul(self)
    }

    /// Multiplicative inverse, by `self^(p−2)`. Returns zero for zero, which is
    /// what every caller here expects.
    pub(crate) fn invert(&self) -> Self {
        let (t19, t3) = self.pow22501();
        t19.pow2k(5).mul(&t3)
    }

    /// "Negative" in the Curve25519 sense: the low bit of the canonical encoding.
    pub(crate) fn is_negative(&self) -> Choice {
        Choice::from(self.as_bytes()[0] & 1)
    }

    /// `sqrt(u/v)`, with the sign and square-detection conventions Curve25519
    /// implementations share.
    ///
    /// Returns `(was_nonzero_square, root)`. When `u/v` is not a square the
    /// returned value is `sqrt(i·u/v)`, which the caller must not use — but which
    /// is still returned so that no branch depends on the outcome.
    ///
    /// The merged inversion/root/square-test is the standard trick:
    /// `sqrt(u/v) = (uv³)·(uv⁷)^((p−5)/8)`, corrected by `sqrt(-1)` when the
    /// check comes out with the wrong sign.
    pub(crate) fn sqrt_ratio_i(u: &Self, v: &Self) -> (Choice, Self) {
        let v3 = v.square().mul(v);
        let v7 = v3.square().mul(v);
        let mut r = u.mul(&v3).mul(&u.mul(&v7).pow_p58());
        let check = v.mul(&r.square());

        let i = Self::sqrt_m1();
        let neg_u = u.neg();

        let correct_sign_sqrt = check.ct_eq(u);
        let flipped_sign_sqrt = check.ct_eq(&neg_u);
        let flipped_sign_sqrt_i = check.ct_eq(&neg_u.mul(&i));

        let r_prime = i.mul(&r);
        r.conditional_assign(&r_prime, flipped_sign_sqrt | flipped_sign_sqrt_i);

        // Canonical root: the non-negative one.
        let r_is_negative = r.is_negative();
        r.conditional_negate(r_is_negative);

        (correct_sign_sqrt | flipped_sign_sqrt, r)
    }

    /// `sqrt(-1)`, i.e. `2^((p−1)/4) mod p`.
    ///
    /// Computed rather than pasted as limbs: a magic constant nobody can check is
    /// worse than four lines that derive it, and this runs once per call site at
    /// negligible cost relative to the exponentiations around it.
    pub(crate) fn sqrt_m1() -> Self {
        // 2^((p-1)/4). (p-1)/4 = 2^253 - 5.
        let two = Self::ONE.add(&Self::ONE);
        let (t19, _) = two.pow22501(); // 2^(2^250 - 1)
        // (2^250 - 1) * 8 + 3 = 2^253 - 5
        t19.pow2k(3).mul(&two.square().mul(&two))
    }

    /// Constant-time equality, returning a `Choice` rather than a `bool`.
    ///
    /// Named to avoid colliding with the `ConstantTimeEq` method while remaining
    /// usable without importing the trait.
    pub(crate) fn ct_eq_fe(&self, other: &Self) -> Choice {
        self.as_bytes().ct_eq(&other.as_bytes())
    }
}

impl ConstantTimeEq for FieldElement {
    fn ct_eq(&self, other: &Self) -> Choice {
        self.as_bytes().ct_eq(&other.as_bytes())
    }
}

impl ConditionallySelectable for FieldElement {
    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
        let mut out = [0u64; 5];
        fiat_25519_selectznz(&mut out, choice.unwrap_u8(), &a.0.0, &b.0.0);
        Self(fiat_25519_tight_field_element(out))
    }
}

impl ConditionallyNegatable for FieldElement {
    fn conditional_negate(&mut self, choice: Choice) {
        let neg = self.neg();
        self.conditional_assign(&neg, choice);
    }
}

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

    fn fe(n: u64) -> FieldElement {
        let mut b = [0u8; 32];
        b[..8].copy_from_slice(&n.to_le_bytes());
        FieldElement::from_bytes(&b)
    }

    #[test]
    fn add_sub_round_trip() {
        let a = fe(12345);
        let b = fe(999);
        assert_eq!(a.add(&b).sub(&b).as_bytes(), a.as_bytes());
    }

    #[test]
    fn negation_is_additive_inverse() {
        let a = fe(7);
        assert_eq!(a.add(&a.neg()).as_bytes(), FieldElement::ZERO.as_bytes());
    }

    #[test]
    fn multiplication_matches_repeated_addition() {
        let a = fe(37);
        let five = fe(5);
        let by_add = a.add(&a).add(&a).add(&a).add(&a);
        assert_eq!(a.mul(&five).as_bytes(), by_add.as_bytes());
    }

    #[test]
    fn square_matches_self_multiplication() {
        let a = fe(0x1234_5678);
        assert_eq!(a.square().as_bytes(), a.mul(&a).as_bytes());
    }

    #[test]
    fn inversion_round_trips() {
        for n in 1..50u64 {
            let a = fe(n);
            assert_eq!(
                a.mul(&a.invert()).as_bytes(),
                FieldElement::ONE.as_bytes(),
                "inversion failed for {n}"
            );
        }
    }

    #[test]
    fn inverting_zero_yields_zero() {
        assert_eq!(
            FieldElement::ZERO.invert().as_bytes(),
            FieldElement::ZERO.as_bytes()
        );
    }

    /// `sqrt(-1)` is the constant everything else leans on, so it is checked by
    /// its defining property rather than against a pasted value.
    #[test]
    fn sqrt_m1_squares_to_minus_one() {
        let i = FieldElement::sqrt_m1();
        assert_eq!(
            i.square().as_bytes(),
            FieldElement::ONE.neg().as_bytes(),
            "sqrt(-1)^2 must be -1"
        );
    }

    #[test]
    fn sqrt_ratio_finds_real_roots() {
        // 4/1 is a square; the root is 2 (chosen non-negative).
        let (ok, r) = FieldElement::sqrt_ratio_i(&fe(4), &FieldElement::ONE);
        assert!(bool::from(ok));
        assert_eq!(r.square().as_bytes(), fe(4).as_bytes());
    }

    #[test]
    fn sqrt_ratio_reports_non_squares() {
        // Exactly half of the nonzero field is square, so a scan finds both.
        let mut squares = 0;
        let mut non_squares = 0;
        for n in 1..80u64 {
            let (ok, r) = FieldElement::sqrt_ratio_i(&fe(n), &FieldElement::ONE);
            if bool::from(ok) {
                squares += 1;
                assert_eq!(r.square().as_bytes(), fe(n).as_bytes());
            } else {
                non_squares += 1;
            }
        }
        assert!(squares > 0 && non_squares > 0, "expected a mix of both");
    }

    #[test]
    fn canonical_roots_are_non_negative() {
        for n in 1..40u64 {
            let (ok, r) = FieldElement::sqrt_ratio_i(&fe(n), &FieldElement::ONE);
            if bool::from(ok) {
                assert!(!bool::from(r.is_negative()), "root of {n} was negative");
            }
        }
    }

    #[test]
    fn conditional_select_picks_the_right_branch() {
        let a = fe(11);
        let b = fe(22);
        assert_eq!(
            FieldElement::conditional_select(&a, &b, Choice::from(0)).as_bytes(),
            a.as_bytes()
        );
        assert_eq!(
            FieldElement::conditional_select(&a, &b, Choice::from(1)).as_bytes(),
            b.as_bytes()
        );
    }

    /// The high bit is not part of a field element. Ignoring this is a classic
    /// source of non-canonical encodings that compare unequal while being equal.
    #[test]
    fn high_bit_is_masked_on_decode() {
        let mut a = [0u8; 32];
        a[0] = 9;
        let mut b = a;
        b[31] |= 0x80;
        assert_eq!(
            FieldElement::from_bytes(&a).as_bytes(),
            FieldElement::from_bytes(&b).as_bytes()
        );
    }
}