Skip to content

Digital Signature — Rust source

Sign messages with Ed25519 or ECDSA and verify signatures. Prove authorship without revealing your private key.

This is the Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.

//! digital-signature — Ed25519 / ECDSA P-256 message signing & verification.
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `digital-signature` tool, ported from
//! src/lib/digital-signature.ts (the canonical TypeScript implementation).
//!
//! Rust's std ships no cryptography at all — there is no WebCrypto to lean on —
//! so, like the Python port, this file implements both algorithms from the
//! integers up: Ed25519 per RFC 8032 and ECDSA over NIST P-256 (SHA-256
//! digest, fresh random nonce per signature, like WebCrypto). Keys are
//! exchanged as hex of the same DER envelopes (SPKI / PKCS8) and signatures
//! are 64 raw bytes (Ed25519 R||S; ECDSA IEEE P1363 r||s), so keys round-trip
//! with the TS/PHP/Python ports. Randomness comes from `RandomState`'s
//! OS-seeded SipHash — display-snippet grade; real deployments want `getrandom`.
//!
//! display source — part of CosmoDev's polyglot tool pages.

use std::cmp::Ordering;
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};

/// Supported signing algorithms, spelled exactly as in the TypeScript union.
pub const ED25519: &str = "ed25519";
pub const ECDSA_P256: &str = "ecdsa-p256";

/// A 256-bit little-endian-limb integer (`[u64; 4]`), the universal currency
/// of this file: every field element and every scalar is one of these.
type U256 = [u64; 4];

const ONE: U256 = [1, 0, 0, 0];

// Ed25519 domain constants (RFC 8032).
/// p = 2^255 - 19, the field prime.
const P_ED: U256 = [
    0xffffffffffffffed,
    0xffffffffffffffff,
    0xffffffffffffffff,
    0x7fffffffffffffff,
];
/// Group order L = 2^252 + 27742317777372353535851937790883648493.
const L_ED: U256 = [
    0x5812631a5cf5d3ed,
    0x14def9dea2f79cd6,
    0,
    0x1000000000000000,
];
/// Curve constant d = -121665/121666 mod p, doubled: the complete extended
/// addition formula consumes 2d.
const D2: U256 = [
    0xeb17676ce4f4b8b7,
    0x7ae1418ba40b98bc,
    0x6fc6bc9e5da41263,
    0x2406d9ca5636a41f,
];
/// y of the base point: 4/5 mod p.
const BASE_Y: U256 = [
    0x6666666666666658,
    0x6666666666666666,
    0x6666666666666666,
    0x6666666666666666,
];
const EXP_P23: U256 = [0xfffffffffffffffc, 0x0fffffffffffffff, 0x0fffffffffffffff, 0x0fffffffffffffff]; // (p+3)/8
const EXP_P14: U256 = [0xfffffffffffffffb, 0xffffffffffffffff, 0xffffffffffffffff, 0x1fffffffffffffff]; // (p-1)/4

// ECDSA P-256 domain constants.
/// Field prime p = 2^256 - 2^224 + 2^192 + 2^96 - 1.
const P_P: U256 = [
    0xffffffffffffffff,
    0x00000000ffffffff,
    0x0000000000000000,
    0xffffffff00000001,
];
/// Group order n.
const N_P: U256 = [
    0xf3b9cac2fc632551,
    0xbce6faada7179e84,
    0xffffffffffffffff,
    0xffffffff00000000,
];
/// Base point G, affine (x, y).
const G_X: U256 = [
    0xf4a13945d898c296,
    0x77037d812deb33a0,
    0xf8bce6e563a440f2,
    0x6b17d1f2e12c4247,
];
const G_Y: U256 = [
    0xcbb6406837bf51f5,
    0x2bce33576b315ece,
    0x8ee7eb4a7c0f9e16,
    0x4fe342e2fe1a7f9b,
];

// Fixed DER envelopes: Ed25519 SPKI wraps the 32-byte point, PKCS8 wraps the
// 32-byte seed (RFC 8410) — both payloads are constant-shaped, like the PHP port.
const ED25519_SPKI_PREFIX: [u8; 12] =
    hex16::<12>("302a300506032b6570032100");
const ED25519_PKCS8_PREFIX: [u8; 16] =
    hex16::<16>("302e020100300506032b657004220420");

/// Compile-time hex decode for the DER prefix constants above (const fn so
/// the envelopes live in .rodata like `const` in every other port).
const fn hex16<const N: usize>(hex: &str) -> [u8; N] {
    let bytes = hex.as_bytes();
    let mut out = [0u8; N];
    let mut i = 0;
    while i < N {
        let hi = (bytes[2 * i] as char).to_digit(16).unwrap() as u8;
        let lo = (bytes[2 * i + 1] as char).to_digit(16).unwrap() as u8;
        out[i] = hi * 16 + lo;
        i += 1;
    }
    out
}

// ---------------------------------------------------------------------------
// 256-bit modular arithmetic: schoolbook 512-bit product + binary long
// division for the reduction. Slow and obvious on purpose — correctness over
// speed for a display snippet.
// ---------------------------------------------------------------------------

fn cmp256(a: &U256, b: &U256) -> Ordering {
    for i in (0..4).rev() {
        if a[i] != b[i] {
            return a[i].cmp(&b[i]);
        }
    }
    Ordering::Equal
}

/// `a - b` mod 2^256 (wrapping; callers ensure a >= b except in reduce/fadd,
/// where the wrap is exactly the 2^256 borrow being resolved by the caller).
fn sub256(a: &U256, b: &U256) -> U256 {
    let mut out = [0u64; 4];
    let mut borrow = 0u64;
    for i in 0..4 {
        let t = (a[i] as i128) - (b[i] as i128) - (borrow as i128);
        out[i] = t as u64;
        borrow = (t < 0) as u64;
    }
    out
}

/// 512-bit product of two 256-bit values, limbs little-endian.
fn mul_wide(a: &U256, b: &U256) -> [u64; 8] {
    let mut out = [0u64; 8];
    for i in 0..4 {
        let mut carry: u128 = 0;
        for j in 0..4 {
            let t = a[i] as u128 * b[j] as u128 + out[i + j] as u128 + carry;
            out[i + j] = t as u64;
            carry = t >> 64;
        }
        let (mut k, mut c) = (i + 4, carry);
        while c > 0 && k < 8 {
            let t = out[k] as u128 + c as u128;
            out[k] = t as u64;
            c = t >> 64;
            k += 1;
        }
    }
    out
}

/// Reduce a 512-bit little-endian-limb value modulo `m` by shifting all 512
/// bits through a 256-bit remainder, subtracting `m` whenever it fits. A
/// textbook binary long division; the `carry` bit tracks the 257th limb.
fn reduce512(x: &[u64; 8], m: &U256) -> U256 {
    let mut rem: U256 = [0, 0, 0, 0];
    for i in (0..512).rev() {
        let mut carry = (x[i / 64] >> (i % 64)) & 1;
        for r in rem.iter_mut() {
            let next = *r >> 63;
            *r = (*r << 1) | carry;
            carry = next;
        }
        if carry == 1 || cmp256(&rem, m) != Ordering::Less {
            // carry == 1 means the true value is 2^256 + rem and the true
            // value - m is < 2^256, so the wrapping subtraction is exact.
            rem = sub256(&rem, m);
        }
    }
    rem
}

/// Field/scalar multiply: (a * b) mod m.
fn fmul(a: &U256, b: &U256, m: &U256) -> U256 {
    reduce512(&mul_wide(a, b), m)
}

/// Field/scalar add: (a + b) mod m, with one conditional subtraction (the sum
/// of two residues is < 2m).
fn fadd(a: &U256, b: &U256, m: &U256) -> U256 {
    let mut out = [0u64; 4];
    let mut carry = 0u64;
    for i in 0..4 {
        let t = a[i] as u128 + b[i] as u128 + carry as u128;
        out[i] = t as u64;
        carry = (t >> 64) as u64;
    }
    if carry == 1 || cmp256(&out, m) != Ordering::Less {
        out = sub256(&out, m);
    }
    out
}

/// Field/scalar subtract: (a - b) mod m; a negative difference wraps once and
/// is pulled back into range by adding m.
fn fsub(a: &U256, b: &U256, m: &U256) -> U256 {
    let d = sub256(a, b);
    if cmp256(a, b) == Ordering::Less {
        fadd(&d, m, m)
    } else {
        d
    }
}

/// Modular exponentiation by LSB-first square-and-multiply.
fn fpow(base: &U256, exp: &U256, m: &U256) -> U256 {
    let mut result = ONE;
    let mut b = *base;
    for i in 0..256 {
        if (exp[i / 64] >> (i % 64)) & 1 == 1 {
            result = fmul(&result, &b, m);
        }
        b = fmul(&b, &b, m);
    }
    result
}

/// Modular inverse via Fermat: a^(m-2) mod m (valid for prime m — both field
/// primes and both group orders here are prime).
fn finv(a: &U256, m: &U256) -> U256 {
    fpow(a, &sub256(m, &[2, 0, 0, 0]), m)
}

// ---------------------------------------------------------------------------
// Hash primitives, hand-rolled because std has none (FIPS 180-4).
// ---------------------------------------------------------------------------

/// SHA-256: digest of `data` as 32 big-endian bytes.
fn sha256(data: &[u8]) -> [u8; 32] {
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
        0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
        0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
        0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
        0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
        0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
        0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
        0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
        0xc67178f2,
    ];
    let mut h: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
        0x5be0cd19,
    ];
    // Pad: 0x80, zeros to 56 mod 64, then the 64-bit big-endian bit length.
    let mut msg = data.to_vec();
    msg.push(0x80);
    while msg.len() % 64 != 56 {
        msg.push(0);
    }
    msg.extend_from_slice(&((data.len() as u64) * 8).to_be_bytes());
    for block in msg.chunks(64) {
        let mut w = [0u32; 64];
        for i in 0..16 {
            w[i] = u32::from_be_bytes(block[4 * i..4 * i + 4].try_into().unwrap());
        }
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
        }
        let mut v = h;
        for i in 0..64 {
            let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
            let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
            let t1 = v[7]
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v = [t2.wrapping_add(t1), v[0], v[1], v[2], v[3].wrapping_add(t1), v[4], v[5], v[6]];
        }
        for i in 0..8 {
            h[i] = h[i].wrapping_add(v[i]);
        }
    }
    let mut out = [0u8; 32];
    for i in 0..8 {
        out[4 * i..4 * i + 4].copy_from_slice(&h[i].to_be_bytes());
    }
    out
}

/// SHA-512: digest of `data` as 64 big-endian bytes (Ed25519's hash).
fn sha512(data: &[u8]) -> [u8; 64] {
    const K: [u64; 80] = [
        0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
        0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
        0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
        0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
        0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
        0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
        0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
        0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
        0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
        0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
        0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
        0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
        0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
        0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
        0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
        0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
        0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
        0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
        0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
        0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817,
    ];
    let mut h: [u64; 8] = [
        0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
        0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
    ];
    let mut msg = data.to_vec();
    msg.push(0x80);
    while msg.len() % 128 != 112 {
        msg.push(0);
    }
    msg.extend_from_slice(&((data.len() as u128) * 8).to_be_bytes());
    for block in msg.chunks(128) {
        let mut w = [0u64; 80];
        for i in 0..16 {
            w[i] = u64::from_be_bytes(block[8 * i..8 * i + 8].try_into().unwrap());
        }
        for i in 16..80 {
            let s0 = w[i - 15].rotate_right(1) ^ w[i - 15].rotate_right(8) ^ (w[i - 15] >> 7);
            let s1 = w[i - 2].rotate_right(19) ^ w[i - 2].rotate_right(61) ^ (w[i - 2] >> 6);
            w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
        }
        let mut v = h;
        for i in 0..80 {
            let s1 = v[4].rotate_right(14) ^ v[4].rotate_right(18) ^ v[4].rotate_right(41);
            let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
            let t1 = v[7]
                .wrapping_add(s1)
                .wrapping_add(ch)
                .wrapping_add(K[i])
                .wrapping_add(w[i]);
            let s0 = v[0].rotate_right(28) ^ v[0].rotate_right(34) ^ v[0].rotate_right(39);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v = [t2.wrapping_add(t1), v[0], v[1], v[2], v[3].wrapping_add(t1), v[4], v[5], v[6]];
        }
        for i in 0..8 {
            h[i] = h[i].wrapping_add(v[i]);
        }
    }
    let mut out = [0u8; 64];
    for i in 0..8 {
        out[8 * i..8 * i + 8].copy_from_slice(&h[i].to_be_bytes());
    }
    out
}

// ---------------------------------------------------------------------------
// Byte plumbing: limbs <-> bytes, hex, PRNG, DER helpers.
// ---------------------------------------------------------------------------

/// Interpret 32 little-endian bytes as a U256.
fn le_bytes_to_u256(b: &[u8]) -> U256 {
    let mut out = [0u64; 4];
    for i in 0..4 {
        out[i] = u64::from_le_bytes(b[8 * i..8 * i + 8].try_into().unwrap());
    }
    out
}

/// Render a U256 as 32 little-endian bytes.
fn u256_to_le_bytes(v: &U256) -> [u8; 32] {
    let mut out = [0u8; 32];
    for i in 0..4 {
        out[8 * i..8 * i + 8].copy_from_slice(&v[i].to_le_bytes());
    }
    out
}

/// Interpret 32 big-endian bytes as a U256 (P-1363 integers are big-endian).
fn be_bytes_to_u256(b: &[u8]) -> U256 {
    let mut out = [0u64; 4];
    for i in 0..4 {
        out[3 - i] = u64::from_be_bytes(b[8 * i..8 * i + 8].try_into().unwrap());
    }
    out
}

/// Render a U256 as 32 big-endian bytes.
fn u256_to_be_bytes(v: &U256) -> [u8; 32] {
    let mut out = [0u8; 32];
    for i in 0..4 {
        out[8 * i..8 * i + 8].copy_from_slice(&v[3 - i].to_be_bytes());
    }
    out
}

/// Lowercase hex encoding, matching the TS lib's `toHex`.
fn to_hex(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0f) as usize] as char);
    }
    out
}

/// Hex decode with the TS lib's `hexToBytes` validation contract.
fn hex_to_bytes(hex: &str, what: &str) -> Result<Vec<u8>, String> {
    let ok = !hex.is_empty() && hex.len() % 2 == 0 && hex.bytes().all(|b| b.is_ascii_hexdigit());
    if !ok {
        return Err(format!("{what} must be a non-empty hex string (pairs of 0-9 / a-f digits)."));
    }
    Ok((0..hex.len() / 2)
        .map(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap())
        .collect())
}

/// Fill `n` bytes with pseudorandom material. std has no CSPRNG, but
/// `RandomState::new()` seeds a fresh SipHash key from OS entropy on every
/// call; hashing a counter through it extends that seed into a byte stream.
fn random_bytes(n: usize) -> Vec<u8> {
    let builder = RandomState::new();
    let mut out = Vec::with_capacity(n);
    for i in 0..n.div_ceil(8) {
        let mut h = builder.build_hasher();
        h.write_u64(i as u64);
        out.extend_from_slice(&h.finish().to_le_bytes());
    }
    out.truncate(n);
    out
}

/// DER TLV builder (definite length, short or long form) — the same encoder
/// the PHP port uses to assemble SPKI / PKCS8 envelopes.
fn der_tlv(tag: u8, content: &[u8]) -> Vec<u8> {
    let mut out = vec![tag];
    match content.len() {
        0..=0x7f => out.push(content.len() as u8),
        0x80..=0xff => out.extend_from_slice(&[0x81, content.len() as u8]),
        _ => {
            let [hi, lo] = (content.len() as u16).to_be_bytes();
            out.extend_from_slice(&[0x82, hi, lo]);
        }
    }
    out.extend_from_slice(content);
    out
}

/// Parse one DER TLV: returns (content, tag, rest), or None on malformed input.
fn der_next(der: &[u8]) -> Option<(&[u8], u8, &[u8])> {
    let (len, hdr) = match der.get(1)? {
        l @ 0..=0x7f => (*l as usize, 2),
        0x81 => (*der.get(2)? as usize, 3),
        0x82 => (((*der.get(2)? as usize) << 8) | *der.get(3)? as usize, 4),
        _ => return None,
    };
    if der.len() < hdr + len {
        return None;
    }
    Some((&der[hdr..hdr + len], der[0], &der[hdr + len..]))
}

// ---------------------------------------------------------------------------
// Ed25519 (RFC 8032): twisted Edwards curve -x^2 + y^2 = 1 + d x^2 y^2, in
// extended coordinates (X:Y:Z:T) with xy == T/Z.
// ---------------------------------------------------------------------------

/// Edwards point in extended coordinates; the identity is (0, 1, 1, 0).
type EdPoint = (U256, U256, U256, U256);

/// The Ed25519 base point: (x, 4/5) with x even, recovered at startup.
fn ed_base() -> EdPoint {
    let x = ed_recover_x(&BASE_Y, 0).expect("base point is on the curve");
    (x, BASE_Y, ONE, fmul(&x, &BASE_Y, &P_ED))
}

/// Solve x^2 = (y^2 - 1) / (d y^2 + 1) mod p and pick the parity (`sign`):
/// a candidate square root that misses is corrected by multiplying with
/// sqrt(-1), and a second miss means y is not on the curve at all.
fn ed_recover_x(y: &U256, sign: u8) -> Option<U256> {
    let yy = fmul(y, y, &P_ED);
    let num = fsub(&yy, &ONE, &P_ED);
    let den = fadd(&fmul(&D2, &yy, &P_ED), &ONE, &P_ED);
    let xx = fmul(&num, &finv(&den, &P_ED), &P_ED);
    let sqrt_m1 = fpow(&[2, 0, 0, 0], &EXP_P14, &P_ED); // sqrt(-1) mod p
    let mut x = fpow(&xx, &EXP_P23, &P_ED);
    if fmul(&x, &x, &P_ED) != xx {
        x = fmul(&x, &sqrt_m1, &P_ED);
    }
    if fmul(&x, &x, &P_ED) != xx {
        return None; // y is not on the curve
    }
    if (x[0] as u8 & 1) != sign & 1 {
        x = fsub(&[0, 0, 0, 0], &x, &P_ED);
    }
    Some(x)
}

/// Unified (complete) extended-coordinate addition, formula "add-2008-hwcd-3"
/// with k = 2d — safe for doubling, so scalar multiplication needs no special
/// doubling path.
fn ed_add(p1: &EdPoint, p2: &EdPoint) -> EdPoint {
    let (x1, y1, z1, t1) = p1;
    let (x2, y2, z2, t2) = p2;
    let a = fmul(&fsub(y1, x1, &P_ED), &fsub(y2, x2, &P_ED), &P_ED);
    let b = fmul(&fadd(y1, x1, &P_ED), &fadd(y2, x2, &P_ED), &P_ED);
    let c = fmul(&fmul(t1, t2, &P_ED), &D2, &P_ED);
    let zz = fmul(z1, z2, &P_ED);
    let d = fadd(&zz, &zz, &P_ED);
    let (e, f, g, h) = (
        fsub(&b, &a, &P_ED),
        fsub(&d, &c, &P_ED),
        fadd(&d, &c, &P_ED),
        fadd(&b, &a, &P_ED),
    );
    (
        fmul(&e, &f, &P_ED),
        fmul(&g, &h, &P_ED),
        fmul(&f, &g, &P_ED),
        fmul(&e, &h, &P_ED),
    )
}

/// Double-and-add scalar multiplication, MSB first. `k` is at most 256 bits.
fn ed_scalarmult(k: &U256, point: &EdPoint) -> EdPoint {
    let mut r: EdPoint = ([0, 0, 0, 0], ONE, ONE, [0, 0, 0, 0]);
    for i in (0..256).rev() {
        r = ed_add(&r, &r);
        if (k[i / 64] >> (i % 64)) & 1 == 1 {
            r = ed_add(&r, point);
        }
    }
    r
}

/// Compress a point: 32 little-endian bytes of y/z with x's low bit in the
/// top byte's high bit (RFC 8032 encoding).
fn ed_compress(p: &EdPoint) -> [u8; 32] {
    let zinv = finv(&p.2, &P_ED);
    let x = fmul(&p.0, &zinv, &P_ED);
    let y = fmul(&p.1, &zinv, &P_ED);
    let mut out = u256_to_le_bytes(&y);
    out[31] |= (x[0] as u8 & 1) << 7;
    out
}

/// Decompress: split off the parity bit, recover x, rebuild (x : y : 1 : xy).
fn ed_decompress(bytes: &[u8; 32]) -> Option<EdPoint> {
    let sign = bytes[31] >> 7;
    let mut y = *bytes;
    y[31] &= 0x7f;
    let y = le_bytes_to_u256(&y);
    let x = ed_recover_x(&y, sign)?;
    Some((x, y, ONE, fmul(&x, &y, &P_ED)))
}

/// Ed25519 secret expansion: SHA-512 of the 32-byte seed, the first half
/// clamped into a valid scalar ("bits" of the private key).
fn ed_expand(seed: &[u8]) -> (U256, [u8; 32]) {
    let h = sha512(seed);
    let mut a = [0u8; 32];
    a.copy_from_slice(&h[..32]);
    a[0] &= 248;
    a[31] &= 127;
    a[31] |= 64;
    (le_bytes_to_u256(&a), {
        let mut tail = [0u8; 32];
        tail.copy_from_slice(&h[32..]);
        tail
    })
}

/// Reduce a SHA-512 digest (a 512-bit little-endian integer per RFC 8032)
/// modulo the group order.
fn ed_hash_to_scalar(digest: &[u8; 64]) -> U256 {
    let mut limbs = [0u64; 8];
    for i in 0..8 {
        limbs[i] = u64::from_le_bytes(digest[8 * i..8 * i + 8].try_into().unwrap());
    }
    reduce512(&limbs, &L_ED)
}

fn ed_public_from_seed(seed: &[u8]) -> [u8; 32] {
    let (a, _) = ed_expand(seed);
    ed_compress(&ed_scalarmult(&a, &ed_base()))
}

/// Generate an Ed25519 key pair: fresh 32-byte seed, PKCS8 = fixed envelope +
/// seed, SPKI = fixed envelope + compressed public point (RFC 8410 shapes).
fn ed25519_generate() -> KeyPair {
    let seed = random_bytes(32);
    let public = ed_public_from_seed(&seed);
    let mut pkcs8 = ED25519_PKCS8_PREFIX.to_vec();
    pkcs8.extend_from_slice(&seed);
    let mut spki = ED25519_SPKI_PREFIX.to_vec();
    spki.extend_from_slice(&public);
    KeyPair { public_key: to_hex(&spki), private_key: to_hex(&pkcs8) }
}

/// Sign `message`: R = [r]B with r = H(prefix || M) mod L, then the challenge
/// k = H(R || A || M) mod L and S = r + k*a mod L. Signature = R || S.
fn ed25519_sign(message: &[u8], seed: &[u8]) -> [u8; 64] {
    let (a, prefix) = ed_expand(seed);
    let public = ed_compress(&ed_scalarmult(&a, &ed_base()));
    let mut r_input = prefix.to_vec();
    r_input.extend_from_slice(message);
    let r = ed_hash_to_scalar(&sha512(&r_input));
    let big_r = ed_compress(&ed_scalarmult(&r, &ed_base()));
    let mut k_input = big_r.to_vec();
    k_input.extend_from_slice(&public);
    k_input.extend_from_slice(message);
    let k = ed_hash_to_scalar(&sha512(&k_input));
    let s = fadd(&r, &fmul(&k, &a, &L_ED), &L_ED);
    let mut sig = [0u8; 64];
    sig[..32].copy_from_slice(&big_r);
    sig[32..].copy_from_slice(&u256_to_le_bytes(&s));
    sig
}

/// Verify: check S < L, then [S]B == R + [k]A with the same challenge k.
fn ed25519_verify(message: &[u8], sig: &[u8; 64], spki: &[u8; 44]) -> bool {
    if spki[..12] != ED25519_SPKI_PREFIX {
        return false;
    }
    let s = le_bytes_to_u256(&sig[32..]);
    if cmp256(&s, &L_ED) != Ordering::Less {
        return false; // non-canonical scalar
    }
    let (Some(point_r), Some(point_a)) = (
        ed_decompress(sig[..32].try_into().unwrap()),
        ed_decompress(spki[12..].try_into().unwrap()),
    ) else {
        return false;
    };
    let mut k_input = sig.to_vec();
    k_input.extend_from_slice(&spki[12..]);
    k_input.extend_from_slice(message);
    let k = ed_hash_to_scalar(&sha512(&k_input));
    ed_compress(&ed_scalarmult(&s, &ed_base())) == ed_compress(&ed_add(&point_r, &ed_scalarmult(&k, &point_a)))
}

// ---------------------------------------------------------------------------
// ECDSA over NIST P-256 (secp256r1): short-Weierstrass y^2 = x^3 - 3x + b,
// Jacobian coordinates (X:Y:Z) with affine x = X/Z^2, y = Y/Z^3, a = 0.
// ---------------------------------------------------------------------------

type Jac = (U256, U256, U256);

/// Jacobian double of (X1, Y1, Z1), formula "dbl-2009-l" for a = 0.
fn p256_dbl(p: &Jac) -> Jac {
    let (x, y, z) = p;
    if *z == [0, 0, 0, 0] || *y == [0, 0, 0, 0] {
        return ([0, 0, 0, 0], ONE, [0, 0, 0, 0]); // point at infinity
    }
    let a = fmul(x, x, &P_P);
    let b = fmul(y, y, &P_P);
    let c = fmul(&b, &b, &P_P);
    let xb = fadd(x, &b, &P_P);
    let d = fadd(
        &fsub(&fmul(&xb, &xb, &P_P), &fadd(&a, &c, &P_P), &P_P),
        &fsub(&fmul(&xb, &xb, &P_P), &fadd(&a, &c, &P_P), &P_P),
        &P_P,
    );
    let e = fadd(&fadd(&a, &a, &P_P), &a, &P_P);
    let f = fmul(&e, &e, &P_P);
    let x3 = fsub(&f, &fadd(&d, &d, &P_P), &P_P);
    let c8 = fadd(&fadd(&fadd(&c, &c, &P_P), &fadd(&c, &c, &P_P), &P_P), &fadd(&fadd(&c, &c, &P_P), &fadd(&c, &c, &P_P), &P_P), &P_P);
    let y3 = fsub(&fmul(&e, &fsub(&d, &x3, &P_P), &P_P), &c8, &P_P);
    let yz = fmul(y, z, &P_P);
    let z3 = fadd(&yz, &yz, &P_P);
    (x3, y3, z3)
}

/// General Jacobian addition, formula "add-2007-bl". Handles infinity and the
/// doubling degeneracy (H == r == 0).
fn p256_add(p1: &Jac, p2: &Jac) -> Jac {
    let (x1, y1, z1) = p1;
    let (x2, y2, z2) = p2;
    if *z1 == [0, 0, 0, 0] {
        return *p2;
    }
    if *z2 == [0, 0, 0, 0] {
        return *p1;
    }
    let z1z1 = fmul(z1, z1, &P_P);
    let z2z2 = fmul(z2, z2, &P_P);
    let u1 = fmul(x1, &z2z2, &P_P);
    let u2 = fmul(x2, &z1z1, &P_P);
    let s1 = fmul(&fmul(y1, z2, &P_P), &z2z2, &P_P);
    let s2 = fmul(&fmul(y2, z1, &P_P), &z1z1, &P_P);
    let h = fsub(&u2, &u1, &P_P);
    let r = fsub(&s2, &s1, &P_P);
    if h == [0, 0, 0, 0] {
        return if r == [0, 0, 0, 0] { p256_dbl(p1) } else { ([0, 0, 0, 0], ONE, [0, 0, 0, 0]) };
    }
    let hh = fmul(&h, &h, &P_P);
    let hhh = fmul(&h, &hh, &P_P);
    let v = fmul(&u1, &hh, &P_P);
    let x3 = fsub(&fsub(&fmul(&r, &r, &P_P), &hhh, &P_P), &fadd(&v, &v, &P_P), &P_P);
    let y3 = fsub(&fmul(&r, &fsub(&v, &x3, &P_P), &P_P), &fmul(&s1, &hhh, &P_P), &P_P);
    let z3 = fmul(&fmul(z1, z2, &P_P), &h, &P_P);
    (x3, y3, z3)
}

/// Double-and-add scalar multiplication of the base point, MSB first.
fn p256_mult_g(k: &U256) -> Jac {
    let mut r: Jac = ([0, 0, 0, 0], ONE, [0, 0, 0, 0]);
    for i in (0..256).rev() {
        r = p256_dbl(&r);
        if (k[i / 64] >> (i % 64)) & 1 == 1 {
            r = p256_add(&r, &(G_X, G_Y, ONE));
        }
    }
    r
}

/// Jacobian scalar multiplication of an arbitrary point (for verify).
fn p256_mult(k: &U256, p: &Jac) -> Jac {
    let mut r: Jac = ([0, 0, 0, 0], ONE, [0, 0, 0, 0]);
    for i in (0..256).rev() {
        r = p256_dbl(&r);
        if (k[i / 64] >> (i % 64)) & 1 == 1 {
            r = p256_add(&r, p);
        }
    }
    r
}

/// Affine x of a Jacobian point: X / Z^2.
fn p256_affine_x(p: &Jac) -> U256 {
    let zinv = finv(&p.2, &P_P);
    fmul(&p.0, &fmul(&zinv, &zinv, &P_P), &P_P)
}

/// Uncompressed SEC1 point 04 || x || y for embedding in the DER envelopes.
fn p256_sec1_point(q: &Jac) -> Vec<u8> {
    let zinv = finv(&q.2, &P_P);
    let zinv2 = fmul(&zinv, &zinv, &P_P);
    let x = fmul(&q.0, &zinv2, &P_P);
    let y = fmul(&q.1, &fmul(&zinv2, &zinv, &P_P), &P_P);
    let mut out = vec![4u8];
    out.extend_from_slice(&u256_to_be_bytes(&x));
    out.extend_from_slice(&u256_to_be_bytes(&y));
    out
}

/// OID contents: 1.2.840.10045.2.1 ecPublicKey, 1.2.840.10045.3.1.7
/// prime256v1 (the same bytes the PHP port hardcodes).
const OID_EC: &[u8] = &hex16::<7>("2a8648ce3d0201");
const OID_P256: &[u8] = &hex16::<8>("2a8648ce3d030107");

/// AlgorithmIdentifier SEQUENCE for an EC key on prime256v1.
fn p256_algorithm_identifier() -> Vec<u8> {
    let mut seq = der_tlv(0x06, OID_EC);
    seq.extend_from_slice(&der_tlv(0x06, OID_P256));
    der_tlv(0x30, &seq)
}

/// Generate a P-256 key pair: random scalar d in [1, n-1], Q = [d]G, exported
/// as hex SPKI / PKCS8 DER assembled around the SEC1 parts.
fn p256_generate() -> KeyPair {
    let d = loop {
        let candidate = be_bytes_to_u256(&random_bytes(32)[..32].try_into().unwrap());
        if candidate != [0, 0, 0, 0] && cmp256(&candidate, &N_P) == Ordering::Less {
            break candidate;
        }
    };
    let q = p256_mult_g(&d);
    let point = p256_sec1_point(&q);
    // SPKI: SEQUENCE { algorithm, BIT STRING (00 || point) }.
    let mut bitstring = vec![0u8];
    bitstring.extend_from_slice(&point);
    let mut spki = p256_algorithm_identifier();
    spki.extend_from_slice(&der_tlv(0x03, &bitstring));
    let spki = der_tlv(0x30, &spki);
    // PKCS8: SEQUENCE { version 0, algorithm, OCTET STRING { SEC1 private key } }.
    let mut sec1 = vec![2u8, 1, 1];
    sec1.extend_from_slice(&der_tlv(0x04, &u256_to_be_bytes(&d)));
    let mut ctx1 = vec![0u8];
    ctx1.extend_from_slice(&point);
    sec1.extend_from_slice(&der_tlv(0xa1, &der_tlv(0x03, &ctx1)));
    let mut pkcs8 = vec![2u8, 1, 0];
    pkcs8.extend_from_slice(&p256_algorithm_identifier());
    pkcs8.extend_from_slice(&der_tlv(0x04, &der_tlv(0x30, &sec1)));
    let pkcs8 = der_tlv(0x30, &pkcs8);
    KeyPair { public_key: to_hex(&spki), private_key: to_hex(&pkcs8) }
}

/// Pull the 32-byte private scalar out of a P-256 PKCS8 document:
/// SEQUENCE { INTEGER 0, algorithm, OCTET STRING { SEQUENCE { INTEGER 1,
/// OCTET STRING d, [1] ... } } }.
fn p256_private_from_pkcs8(der: &[u8]) -> Option<[u8; 32]> {
    let (seq, 0x30, rest) = der_next(der)? else { return None };
    let _ = rest;
    let (_, 0x02, body) = der_next(seq)? else { return None }; // version 0
    let (alg, 0x30, body) = der_next(body)? else { return None };
    der_next(alg)?; // algorithm AlgorithmIdentifier
    let (octet, 0x04, rest) = der_next(body)? else { return None };
    if !rest.is_empty() {
        return None;
    }
    let (sec1, 0x30, rest) = der_next(octet)? else { return None };
    if !rest.is_empty() {
        return None;
    }
    let (_, 0x02, sec1) = der_next(sec1)? else { return None }; // version 1
    let (d, 0x04, rest) = der_next(sec1)? else { return None };
    if !rest.is_empty() || d.len() != 32 {
        return None;
    }
    Some(d.try_into().unwrap())
}

/// Pull (x, y) out of a P-256 SPKI document: SEQUENCE { algorithm,
/// BIT STRING (00 04 || x || y) }.
fn p256_point_from_spki(der: &[u8]) -> Option<(U256, U256)> {
    let (seq, 0x30, rest) = der_next(der)? else { return None };
    if !rest.is_empty() {
        return None;
    }
    let (alg, 0x30, body) = der_next(seq)? else { return None };
    der_next(alg)?; // algorithm AlgorithmIdentifier
    let (bits, 0x03, rest) = der_next(body)? else { return None };
    if !rest.is_empty() || bits.len() != 65 || bits[0] != 0 || bits[1] != 4 {
        return None;
    }
    Some((be_bytes_to_u256(&bits[2..34]), be_bytes_to_u256(&bits[34..66])))
}

/// Sign `message`: ECDSA with SHA-256 digest e and a fresh random nonce k
/// (WebCrypto-style — signatures differ per call, unlike the Python port's
/// deterministic RFC 6979 nonces; both verify against the same keys).
/// Output is the 64-byte IEEE P1363 r||s, hex-encoded.
fn p256_sign(message: &[u8], d: &U256) -> [u8; 64] {
    let e = be_bytes_to_u256(&sha256(message));
    loop {
        let k = loop {
            let candidate = be_bytes_to_u256(&random_bytes(32)[..32].try_into().unwrap());
            if candidate != [0, 0, 0, 0] && cmp256(&candidate, &N_P) == Ordering::Less {
                break candidate;
            }
        };
        // r = affine x of [k]G, reduced mod n (x < p but may exceed n).
        let x = u256_to_be_bytes(&p256_affine_x(&p256_mult_g(&k)));
        let mut x_limbs = [0u64; 8];
        x_limbs[..4].copy_from_slice(&be_bytes_to_u256(&x));
        let r = reduce512(&x_limbs, &N_P);
        if r == [0, 0, 0, 0] {
            continue;
        }
        let s = fmul(&finv(&k, &N_P), &fadd(&e, &fmul(&r, d, &N_P), &N_P), &N_P);
        if s != [0, 0, 0, 0] {
            let mut sig = [0u8; 64];
            sig[..32].copy_from_slice(&u256_to_be_bytes(&r));
            sig[32..].copy_from_slice(&u256_to_be_bytes(&s));
            return sig;
        }
    }
}

/// Verify P-1363 r||s: reject out-of-range r/s, then u1 = e/s and
/// u2 = r/s must satisfy x([u1]G + [u2]Q) == r (mod n).
fn p256_verify(message: &[u8], sig: &[u8], q: &(U256, U256)) -> bool {
    let r = be_bytes_to_u256(&sig[..32]);
    let s = be_bytes_to_u256(&sig[32..]);
    if r == [0, 0, 0, 0] || s == [0, 0, 0, 0] || cmp256(&r, &N_P) != Ordering::Less || cmp256(&s, &N_P) != Ordering::Less {
        return false;
    }
    let e = be_bytes_to_u256(&sha256(message));
    let sinv = finv(&s, &N_P);
    let u1 = fmul(&e, &sinv, &N_P);
    let u2 = fmul(&r, &sinv, &N_P);
    let point = p256_add(&p256_mult(&u1, &(G_X, G_Y, ONE)), &p256_mult(&u2, &(q.0, q.1, ONE)));
    if point.2 == [0, 0, 0, 0] {
        return false; // result at infinity -> invalid signature
    }
    let x = u256_to_be_bytes(&p256_affine_x(&point));
    let mut x_limbs = [0u64; 8];
    x_limbs[..4].copy_from_slice(&be_bytes_to_u256(&x));
    reduce512(&x_limbs, &N_P) == r
}

// ---------------------------------------------------------------------------
// Public API — the three lib entry points, with the same contracts: verify
// returns false on mismatch, and only malformed input is an error.
// ---------------------------------------------------------------------------

/// Hex-encoded SPKI / PKCS8 key halves, exactly the lib's `KeyPair` shape.
pub struct KeyPair {
    /// Hex-encoded SPKI (SubjectPublicKeyInfo) public key. Safe to share.
    pub public_key: String,
    /// Hex-encoded PKCS8 private key. Keep it secret — it IS the identity.
    pub private_key: String,
}

/// Throws unless `algorithm` is one of the two supported values.
fn assert_algorithm(algorithm: &str) -> Result<(), String> {
    if algorithm != ED25519 && algorithm != ECDSA_P256 {
        return Err(format!("Unknown algorithm. Use \"{ED25519}\" or \"{ECDSA_P256}\"."));
    }
    Ok(())
}

fn label(algorithm: &str) -> &'static str {
    if algorithm == ED25519 { "Ed25519" } else { "ECDSA P-256" }
}

/// Generate a fresh signing key pair, exported as hex SPKI / PKCS8 keys.
pub fn generate_key_pair(algorithm: &str) -> Result<KeyPair, String> {
    assert_algorithm(algorithm)?;
    Ok(if algorithm == ED25519 { ed25519_generate() } else { p256_generate() })
}

/// Sign `message` with a hex PKCS8 private key. Returns the hex signature.
pub fn sign_message(message: &str, private_key_hex: &str, algorithm: &str) -> Result<String, String> {
    assert_algorithm(algorithm)?;
    if message.is_empty() {
        return Err("Message must not be empty.".to_string());
    }
    let key = hex_to_bytes(private_key_hex, "Private key")?;
    let msg = message.as_bytes();
    if algorithm == ED25519 {
        if key.len() != 48 || key[..16] != ED25519_PKCS8_PREFIX {
            return Err(format!("Invalid private key for {} (expected hex PKCS8).", label(algorithm)));
        }
        let seed: [u8; 32] = key[16..].try_into().unwrap();
        Ok(to_hex(&ed25519_sign(msg, &seed)))
    } else {
        let Some(der) = der_full(&key) else {
            return Err(format!("Invalid private key for {} (expected hex PKCS8).", label(algorithm)));
        };
        let Some(d) = p256_private_from_pkcs8(der) else {
            return Err(format!("Invalid private key for {} (expected hex PKCS8).", label(algorithm)));
        };
        Ok(to_hex(&p256_sign(msg, &be_bytes_to_u256(&d))))
    }
}

/// Verify `signature_hex` against `message` with a hex SPKI public key.
/// Returns false when the signature, message or key simply do not match;
/// errors only for malformed input (non-hex / wrong key type).
pub fn verify_signature(message: &str, signature_hex: &str, public_key_hex: &str, algorithm: &str) -> Result<bool, String> {
    assert_algorithm(algorithm)?;
    let signature = hex_to_bytes(signature_hex, "Signature")?;
    if signature.len() != 64 {
        return Ok(false); // never a valid signature for either algorithm
    }
    let key = hex_to_bytes(public_key_hex, "Public key")?;
    let msg = message.as_bytes();
    if algorithm == ED25519 {
        if key.len() != 44 || key[..12] != ED25519_SPKI_PREFIX {
            return Err(format!("Invalid public key for {} (expected hex SPKI).", label(algorithm)));
        }
        let mut sig = [0u8; 64];
        sig.copy_from_slice(&signature);
        let spki: [u8; 44] = key.try_into().unwrap();
        Ok(ed25519_verify(msg, &sig, &spki))
    } else {
        let Some(der) = der_full(&key) else {
            return Err(format!("Invalid public key for {} (expected hex SPKI).", label(algorithm)));
        };
        let Some((x, y)) = p256_point_from_spki(der) else {
            return Err(format!("Invalid public key for {} (expected hex SPKI).", label(algorithm)));
        };
        Ok(p256_verify(msg, &signature, &(x, y)))
    }
}

/// Wrap a byte slice as `&[u8]` or reject trailing structure: the DER walkers
/// above already check trailing bytes, this just unifies the borrow shapes.
fn der_full(der: &[u8]) -> Option<&[u8]> {
    (!der.is_empty()).then_some(der)
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →