garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /crypto/src/ed25519.rs

raw

//! Ed25519 signatures (RFC 8032): points on the twisted Edwards curve
//! −x² + y² = 1 + d·x²·y² in extended coordinates (X:Y:Z:T), with complete
//! addition formulas, and constant-time scalar multiplication.

use crate::field::Fe;
use crate::scalar;
use crate::sha2::Sha512;

#[derive(Clone, Copy)]
struct Point {
    x: Fe,
    y: Fe,
    z: Fe,
    t: Fe,
}

/// d = −121665 / 121666.
fn d() -> Fe {
    Fe::from_u64(121_665).neg().mul(Fe::from_u64(121_666).invert())
}

/// √−1 = 2^((p − 1) / 4).
fn sqrt_m1() -> Fe {
    // (p − 1) / 4 = 2^253 − 5: 2 to it, by squaring 2 to 2^252 − 3 ... done
    // through pow_p58: 2^((p−5)/8) squared and times 2 gives 2^((p−1)/4).
    let two = Fe::from_u64(2);
    two.pow_p58().square().mul(two)
}

impl Point {
    const IDENTITY: Point = Point {
        x: Fe::ZERO,
        y: Fe::ONE,
        z: Fe::ONE,
        t: Fe::ZERO,
    };

    fn add(&self, q: &Point, d2: Fe) -> Point {
        let a = self.y.sub(self.x).mul(q.y.sub(q.x));
        let b = self.y.add(self.x).mul(q.y.add(q.x));
        let c = self.t.mul(d2).mul(q.t);
        let dd = self.z.add(self.z).mul(q.z);
        let (e, f, g, h) = (b.sub(a), dd.sub(c), dd.add(c), b.add(a));
        Point {
            x: e.mul(f),
            y: g.mul(h),
            t: e.mul(h),
            z: f.mul(g),
        }
    }

    fn select(&self, q: &Point, choose: u64) -> Point {
        Point {
            x: self.x.select(q.x, choose),
            y: self.y.select(q.y, choose),
            z: self.z.select(q.z, choose),
            t: self.t.select(q.t, choose),
        }
    }

    fn neg(&self) -> Point {
        Point {
            x: self.x.neg(),
            y: self.y,
            z: self.z,
            t: self.t.neg(),
        }
    }

    /// scalar × self, the same work whatever the scalar's bits.
    fn mul(&self, scalar: &[u8; 32]) -> Point {
        let d2 = d().add(d());
        let mut acc = Point::IDENTITY;
        for bit in (0..256).rev() {
            acc = acc.add(&acc, d2);
            let sum = acc.add(self, d2);
            acc = acc.select(&sum, u64::from((scalar[bit / 8] >> (bit % 8)) & 1));
        }
        acc
    }

    fn compress(&self) -> [u8; 32] {
        let zi = self.z.invert();
        let (x, y) = (self.x.mul(zi), self.y.mul(zi));
        let mut out = y.to_bytes();
        out[31] |= (x.is_negative() as u8) << 7;
        out
    }

    fn decompress(bytes: &[u8; 32]) -> Option<Point> {
        let sign = u64::from(bytes[31] >> 7);
        let y = Fe::from_bytes(bytes);
        let mut canonical = *bytes;
        canonical[31] &= 0x7f;
        if !crate::equal(&y.to_bytes(), &canonical) {
            return None;
        }
        let y2 = y.square();
        let u = y2.sub(Fe::ONE);
        let v = d().mul(y2).add(Fe::ONE);
        // x = u·v³·(u·v⁷)^((p−5)/8), then fixed by √−1 if it squares to −u/v.
        let v3 = v.square().mul(v);
        let v7 = v3.square().mul(v);
        let mut x = u.mul(v3).mul(u.mul(v7).pow_p58());
        let check = v.mul(x.square());
        if check.equals(u.neg()) {
            x = x.mul(sqrt_m1());
        } else if !check.equals(u) {
            return None;
        }
        if x.is_zero() && sign == 1 {
            return None;
        }
        if x.is_negative() != sign {
            x = x.neg();
        }
        Some(Point {
            x,
            y,
            z: Fe::ONE,
            t: x.mul(y),
        })
    }
}

fn base() -> Point {
    // y = 4/5, x positive (even).
    let mut y = Fe::from_u64(4).mul(Fe::from_u64(5).invert()).to_bytes();
    y[31] &= 0x7f;
    Point::decompress(&y).expect("the base point decompresses")
}

/// The secret scalar and the nonce prefix of a 32-byte secret key.
fn expand(secret: &[u8; 32]) -> ([u8; 32], [u8; 32]) {
    let h = Sha512::digest(secret);
    let mut a: [u8; 32] = h[..32].try_into().unwrap();
    a[0] &= 248;
    a[31] &= 127;
    a[31] |= 64;
    (a, h[32..].try_into().unwrap())
}

/// The public key of a secret key.
pub fn public(secret: &[u8; 32]) -> [u8; 32] {
    base().mul(&expand(secret).0).compress()
}

pub fn sign(secret: &[u8; 32], message: &[u8]) -> [u8; 64] {
    let (a, prefix) = expand(secret);
    let b = base();
    let public = b.mul(&a).compress();
    let mut h = Sha512::new();
    h.update(&prefix);
    h.update(message);
    let r = scalar::reduce(&h.finish());
    let big_r = b.mul(&r).compress();
    let mut h = Sha512::new();
    h.update(&big_r);
    h.update(&public);
    h.update(message);
    let k = scalar::reduce(&h.finish());
    let s = scalar::mul_add(&k, &a, &r);
    let mut signature = [0u8; 64];
    signature[..32].copy_from_slice(&big_r);
    signature[32..].copy_from_slice(&s);
    signature
}

pub fn verify(public: &[u8; 32], message: &[u8], signature: &[u8; 64]) -> bool {
    let Some(a) = Point::decompress(public) else {
        return false;
    };
    let s: [u8; 32] = signature[32..].try_into().unwrap();
    if !scalar::is_canonical(&s) {
        return false;
    }
    let mut h = Sha512::new();
    h.update(&signature[..32]);
    h.update(public);
    h.update(message);
    let k = scalar::reduce(&h.finish());
    // S·B − k·A must be R.
    let d2 = d().add(d());
    let check = base().mul(&s).add(&a.mul(&k).neg(), d2);
    crate::equal(&check.compress(), &signature[..32])
}