Skip to content
Blog

← All articles

Elliptic Curves for Programmers: The Math Behind ES256 and Ed25519, and How the PS3 Key Leaked

Elliptic-curve cryptography from the ground up, in runnable code: point addition on a curve you can draw, P-256 and ECDSA (ES256) written from scratch and checked against Node, the PS3 hack that recovered a private key from two signatures sharing a nonce, Ed25519 built byte for byte to RFC 8032 and why its nonces are deterministic, and what it all means for JWTs.

By 22 min read

In December 2010, a group of hackers called fail0verflow stood on stage at the Chaos Communication Congress in Berlin and explained how they had broken the PlayStation 3. Sony signed every piece of code the console would run with ECDSA, the same elliptic-curve signature algorithm behind ES256 tokens. The math was sound. But ECDSA needs a fresh random number for every signature, and Sony used the same one every time. From two signatures, anyone could compute Sony’s private signing key with high-school algebra, and then sign anything.

This article explains the math that made that possible, and the design that makes it impossible in Ed25519. It picks up where the RSA article left off: the same modular arithmetic, applied to points on a curve instead of plain numbers. We’ll build a curve small enough to list every point, then P-256 and ECDSA from scratch (checked against Node’s crypto in both directions), run the PS3 attack on a real key, implement Ed25519 byte for byte to its RFC, and see what all of it means for JWTs. Every example ran on Node.js 24 before publishing, and every number below comes from those runs.

The short answer#

Why not just use RSA?#

RSA works, but its keys are huge, and they keep growing. Its security rests on factoring, and the best factoring algorithm, the general number field sieve, is much faster than trying every possibility. To stay ahead, RSA keys have to be thousands of bits long. For elliptic curves, no comparable shortcut is known: the best general attack, Pollard’s rho, takes about √n steps for a group of n points. A 256-bit curve therefore offers about 2128 work, the same as 3,072-bit RSA. NIST’s equivalence table (SP 800-57):

Security levelRSA modulusElliptic curveExamples
128 bits3,072 bits256 bitsP-256 (ES256), Curve25519 (Ed25519)
192 bits7,680 bits384 bitsP-384 (ES384)
256 bits15,360 bits512 bitsP-521 (ES512)

Neal Koblitz and Victor Miller independently proposed elliptic curves for cryptography in 1985. It took about 20 years for them to become mainstream, partly because of patents and partly because the math is less familiar. Today they’re everywhere: almost every TLS connection agrees on its keys using X25519 (often combined with a post-quantum algorithm) or P-256; Bitcoin signs transactions with a curve called secp256k1; and Signal, SSH, and WireGuard use Curve25519.

A curve you can draw#

An elliptic curve (nothing to do with ellipses; the name comes from the integrals used to measure ellipses) is the set of points satisfying an equation of the form:

Over the real numbers, it’s a smooth curve, symmetric about the x-axis. The interesting part is that you can “add” two points on it and get a third, with a rule called chord and tangent: draw a straight line through P and Q. It always meets the curve at exactly one more point. Reflect that point across the x-axis, and you have P + Q.

PQ−(P + Q)P + Qy² = x³ − x + 1
Adding P and Q: the line through them meets the curve again at −(P + Q); its mirror image is P + Q.

Two special cases complete the rule. To add a point to itself (doubling), use the tangent line at that point. And when the line is vertical, as it is for a point and its mirror image, there’s no third point, so we invent one: the point at infinity, written ∞ or O, which plays the role of zero (P + ∞ = P). With those rules, the points form a group: addition is associative, every point has a negative, and the order of additions doesn’t matter. That’s exactly the structure cryptography needs.

The formulas come from finding where the line meets the cubic. For two different points, the slope is λ = (yQ − yP) / (xQ − xP); for doubling, it’s the tangent’s slope, λ = (3xP² + a) / 2yP. Then x = λ² − xP − xQ and y = λ(xP − x) − yP. That’s all the code will need.

The same curve, modulo a prime#

Real numbers are no good for cryptography: they’re imprecise, and the curve’s shape gives away too much. So we do all the arithmetic modulo a prime p, exactly like RSA does. Division becomes multiplication by a modular inverse. The “curve” is no longer a curve, just a scattered set of points with whole-number coordinates, but the same formulas still work, and the points still form a group.

Here’s a curve small enough to see completely: y² = x³ + 2x + 2, modulo 17.

toy-curve.mjs
// toy-curve.mjs: an elliptic curve small enough to see every point. y² = x³ + 2x + 2 over the integers mod 17.
const p = 17n, a = 2n, b = 2n;
const mod = (x) => ((x % p) + p) % p;
const inv = (x) => { for (let i = 1n; i < p; i++) if (mod(x * i) === 1n) return i; throw new Error("no inverse"); };

// "Adding" two points: draw the line through them, find the third point where it meets the curve, and reflect it.
// null is the point at infinity, the identity: P + null = P.
function add(P, Q) {
  if (!P) return Q;
  if (!Q) return P;
  if (P[0] === Q[0] && mod(P[1] + Q[1]) === 0n) return null; // P + (−P): a vertical line
  const slope = P[0] === Q[0] && P[1] === Q[1]
    ? mod((3n * P[0] * P[0] + a) * inv(2n * P[1])) // doubling: the tangent's slope
    : mod((Q[1] - P[1]) * inv(Q[0] - P[0])); // two points: the chord's slope
  const x = mod(slope * slope - P[0] - Q[0]);
  return [x, mod(slope * (P[0] - x) - P[1])];
}

// Every point on the curve: try every x and y.
const points = [];
for (let x = 0n; x < p; x++) for (let y = 0n; y < p; y++) if (mod(y * y - (x * x * x + a * x + b)) === 0n) points.push([x, y]);
console.log(`${points.length} points, plus the point at infinity`);

// Keep adding G to itself: it visits every point, then returns to the start.
const G = [5n, 1n];
let P = G;
const multiples = [];
for (let k = 1; P; k++) { multiples.push(`${k}G=(${P})`); P = add(P, G); }
console.log(multiples.join(" "), `${multiples.length + 1}G=∞`);

// The private key is a number k, the public key is kG. Going back means trying every k.
const Q = [13n, 7n];
let k = 1, R = G;
while (R[0] !== Q[0] || R[1] !== Q[1]) { R = add(R, G); k++; }
console.log(`(${Q}) = ${k}G, found after ${k} tries`);
18 points, plus the point at infinity
1G=(5,1) 2G=(6,3) 3G=(10,6) 4G=(3,1) 5G=(9,16) 6G=(16,13) 7G=(0,6) 8G=(13,7) 9G=(7,6) 10G=(7,11) 11G=(13,10) 12G=(0,11) 13G=(16,4) 14G=(9,1) 15G=(3,16) 16G=(10,11) 17G=(6,14) 18G=(5,16) 19G=∞
(13,7) = 8G, found after 8 tries

Start at G = (5, 1) and keep adding G: the sequence jumps around the 18 points in no visible pattern, lands on ∞ at 19G, and then repeats. The number of steps before it returns, 19, is G’s order, written n. Every private key is a number below n.

The one-way street#

Pick a secret number d and compute Q = d·G, meaning G added to itself d times. That’s an elliptic-curve key pair: d is the private key, the point Q is the public key.

Computing Q is fast even for a 256-bit d, because you never add G one step at a time. You use double-and-add, the curve version of the square-and-multiply trick from the RSA article: walk through the bits of d, doubling at each bit and adding G when the bit is 1. A 256-bit d takes about 256 doublings and 128 additions.

Going backward, from Q to d, is the elliptic-curve discrete logarithm problem. On the toy curve, the script just tried every multiple and found (13, 7) = 8G after 8 tries. On a real curve, n is about 2256, the multiples look random, and the best known attack still needs around 2128 steps. At a billion billion steps per second, that’s about ten thousand billion years. That asymmetry, easy forward and infeasible backward, is what every elliptic-curve scheme is built on.

P-256 from scratch#

P-256 (also called secp256r1 or prime256v1) is the curve behind ES256. It was standardized by NIST around 2000 and is used in TLS, passkeys, and smart cards. It’s the toy curve with bigger numbers: a = −3, a 256-bit prime p, a fixed b and base point G, and a prime order n:

p256.mjs
// p256.mjs: the curve behind ES256, in about 40 lines of BigInt. Same formulas as the toy curve, bigger numbers.
// y² = x³ − 3x + b over the integers mod p, with the base point G and its order n from FIPS 186.
export const p = 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn;
export const a = p - 3n;
export const b = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn;
export const n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n;
export const G = [
  0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,
  0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,
];

export const mod = (x, m = p) => ((x % m) + m) % m;

// The modular inverse, by the extended Euclidean algorithm (as in the RSA article).
export function inv(x, m = p) {
  let [r0, r1, s0, s1] = [mod(x, m), m, 1n, 0n];
  while (r1 !== 0n) {
    const q = r0 / r1;
    [r0, r1, s0, s1] = [r1, r0 - q * r1, s1, s0 - q * s1];
  }
  if (r0 !== 1n) throw new Error("no inverse");
  return mod(s0, m);
}

export function add(P, Q) {
  if (!P) return Q;
  if (!Q) return P;
  if (P[0] === Q[0] && mod(P[1] + Q[1]) === 0n) return null;
  const slope = P[0] === Q[0]
    ? mod((3n * P[0] * P[0] + a) * inv(2n * P[1]))
    : mod((Q[1] - P[1]) * inv(Q[0] - P[0]));
  const x = mod(slope * slope - P[0] - Q[0]);
  return [x, mod(slope * (P[0] - x) - P[1])];
}

// k·P by double-and-add: about 256 doublings and 128 additions, instead of k additions.
export function mul(k, P = G) {
  let R = null;
  for (let bit = BigInt(k.toString(2).length) - 1n; bit >= 0n; bit--) {
    R = add(R, R);
    if ((k >> bit) & 1n) R = add(R, P);
  }
  return R;
}

export const onCurve = ([x, y]) => mod(y * y - (x * x * x + a * x + b)) === 0n;

That’s the entire curve. The test for this article checks that G is on the curve, that n·G is the point at infinity, and that for ten keys generated by Node, mul(d) gives exactly the public key Node reports. This code is for understanding, not for production: it isn’t constant-time, so how long it takes depends on the secret, and an attacker who can time it could learn the key. Real libraries use carefully constant-time arithmetic. Use them.

ECDSA: how ES256 signs#

The Elliptic Curve Digital Signature Algorithm takes a private key d, the message’s SHA-256 hash as a number z, and one more ingredient: a fresh, secret, random number k, the nonce.

The signature is the pair (r, s), two 256-bit numbers: 64 bytes. To verify it with the public key Q, compute w = s⁻¹, then compute the point u1·G + u2·Q, with u1 = z·w and u2 = r·w. If its x-coordinate equals r, the signature is valid. It works because Q = d·G, so that point is w·(z + r·d)·G, and the signing equation says z + r·d = s·k, so it’s w·s·k·G = k·G, the very point that produced r. Here’s ECDSA, checked against Node in both directions:

ecdsa.mjs
// ecdsa.mjs: ECDSA on P-256 (ES256) from scratch, checked against Node's crypto in both directions.
import { createHash, generateKeyPairSync, randomBytes, sign, verify } from "node:crypto";
import { add, inv, mod, mul, n } from "./p256.mjs";

export const hash = (msg) => BigInt("0x" + createHash("sha256").update(msg).digest("hex")); // z, the message as a number
const big = (b64url) => BigInt("0x" + Buffer.from(b64url, "base64url").toString("hex"));
const hex32 = (x) => x.toString(16).padStart(64, "0");

// Sign: pick a secret one-time number k (the nonce), and publish r = (k·G).x and s = k⁻¹(z + r·d).
export function ecdsaSign(d, msg, k) {
  const r = mod(mul(k)[0], n);
  const s = mod(inv(k, n) * (hash(msg) + r * d), n);
  return { r, s };
}

// Verify: u1·G + u2·Q is the same point k·G, but only if s was made with the private key behind Q.
export function ecdsaVerify(Q, msg, { r, s }) {
  const w = inv(s, n);
  const X = add(mul(mod(hash(msg) * w, n)), mul(mod(r * w, n), Q));
  return X !== null && mod(X[0], n) === r;
}

// JWS (ES256) and Node's "ieee-p1363" format: r and s as two 32-byte numbers, back to back.
export const toP1363 = ({ r, s }) => Buffer.from(hex32(r) + hex32(s), "hex");
export const fromP1363 = (buf) => ({ r: BigInt("0x" + buf.toString("hex", 0, 32)), s: BigInt("0x" + buf.toString("hex", 32)) });
export const keyFromJwk = (jwk) => ({ d: jwk.d && big(jwk.d), Q: [big(jwk.x), big(jwk.y)] });

if (process.argv[1]?.endsWith("ecdsa.mjs")) {
  const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
  const { d, Q } = keyFromJwk(privateKey.export({ format: "jwk" }));
  const dG = mul(d);
  console.log("public key = d·G:", dG[0] === Q[0] && dG[1] === Q[1]);

  const msg = "pay 10 coins to alice";
  const k = mod(BigInt("0x" + randomBytes(32).toString("hex")), n);
  const ours = ecdsaSign(d, msg, k);
  console.log("Node verifies our signature:", verify("sha256", Buffer.from(msg), { key: publicKey, dsaEncoding: "ieee-p1363" }, toP1363(ours)));
  const nodes = fromP1363(sign("sha256", Buffer.from(msg), { key: privateKey, dsaEncoding: "ieee-p1363" }));
  console.log("we verify Node's signature:", ecdsaVerify(Q, msg, nodes));
  console.log("a different message fails:", ecdsaVerify(Q, "pay 99 coins to mallory", nodes));
  // (r, n − s) verifies too: one message, two valid signatures. The JWS article calls these "twins".
  console.log("(r, n − s) also verifies:", ecdsaVerify(Q, msg, { r: nodes.r, s: n - nodes.s }));
}
public key = d·G: true
Node verifies our signature: true
we verify Node's signature: true
a different message fails: false
(r, n − s) also verifies: true

The test signs 20 messages each way, and also confirms the last line with Node itself: if (r, s) is valid, so is (r, n − s). One message has two valid ECDSA signatures, which matters when something treats the signature as unique; the JWS mechanics article calls these “twins” and shows what they do to tokens.

Now look again at the signing equation. It contains two secrets, d and k, and everything else is public. One signature is one equation with two unknowns: safe. The whole security of ECDSA depends on k staying secret and never being used twice.

The PS3 hack: one repeated nonce#

The PlayStation 3 would only run code signed by Sony, and its security design was otherwise strong. But Sony’s signing process used the same k for every signature. fail0verflow noticed the giveaway: every signature had the same r, because r depends only on k. Two signatures with the same k give two equations with the same two unknowns, and that’s solvable:

Here it is against a real P-256 key. The signer has one bug: it picks a random k once and keeps using it. The attacker only sees what a signature ever reveals: the public key, the messages, and the signatures.

ps3.mjs
// ps3.mjs: the PS3 mistake. A signer that reuses its nonce k gives away its private key, and the attacker then signs
// anything they like with it. Node's own crypto.verify accepts the forgery.
import { createPublicKey, generateKeyPairSync, randomBytes, verify } from "node:crypto";
import { ecdsaSign, fromP1363, hash, keyFromJwk, toP1363 } from "./ecdsa.mjs";
import { inv, mod, n } from "./p256.mjs";

// --- The victim: a real P-256 key, and a signer with one fatal bug. ---
const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
const { d } = keyFromJwk(privateKey.export({ format: "jwk" }));
const k = mod(BigInt("0x" + randomBytes(32).toString("hex")), n); // random... but chosen once and used for ever
const signBuggy = (msg) => toP1363(ecdsaSign(d, msg, k));

const m1 = "update 3.55", m2 = "update 3.56";
const sig1 = signBuggy(m1), sig2 = signBuggy(m2);
console.log("both signatures verify:", [[m1, sig1], [m2, sig2]].every(([m, s]) =>
  verify("sha256", Buffer.from(m), { key: publicKey, dsaEncoding: "ieee-p1363" }, s)));

// --- The attacker: sees only the public key, the two messages, and the two signatures. ---
const a = fromP1363(sig1), b = fromP1363(sig2);
console.log("same r in both signatures:", a.r === b.r); // the giveaway: r depends only on k
// s1 − s2 = k⁻¹(z1 − z2), so k = (z1 − z2) / (s1 − s2). Then s1 = k⁻¹(z1 + r·d) gives d = (s1·k − z1) / r.
const z1 = hash(m1), z2 = hash(m2);
const kFound = mod((z1 - z2) * inv(a.s - b.s, n), n);
const dFound = mod((a.s * kFound - z1) * inv(a.r, n), n);
console.log("recovered k:", kFound === k);
console.log("recovered private key:", dFound === d);

// With d, the attacker signs a message of their own, with a fresh nonce, and it verifies against the real public key.
const evil = "update 6.66: run anything";
const forged = toP1363(ecdsaSign(dFound, evil, mod(BigInt("0x" + randomBytes(32).toString("hex")), n)));
const pub = createPublicKey(publicKey.export({ format: "pem", type: "spki" }));
console.log("forged signature verifies:", verify("sha256", Buffer.from(evil), { key: pub, dsaEncoding: "ieee-p1363" }, forged));
both signatures verify: true
same r in both signatures: true
recovered k: true
recovered private key: true
forged signature verifies: true

The last line is the one that matters: with the recovered key, the attacker signs a message of their own choosing, and Node’s crypto.verify, given only the real public key, accepts it. The test runs the attack ten times on ten fresh keys, and it works every time. For the PS3, that meant anyone could sign software as Sony, and within weeks the console’s master signing key was public. A key burned into millions of consoles can’t be replaced.

Sony’s bug was extreme, but the nonce doesn’t need to repeat exactly to leak the key. In 2013, a flaw in Android’s SecureRandom caused some Bitcoin wallet apps to reuse nonces, and attackers swept the coins out of the affected addresses. In 2019, the TPM-Fail and Minerva research showed that a timing leak revealing just a few bits of each nonce was enough: with enough signatures, a lattice-reduction algorithm recovered the full key. ECDSA’s nonce must be secret, unique, and unbiased, every time, forever. The CSPRNG article covers where good randomness comes from.

Try the attack in your browser#

This runs the same attack with a brand-new P-256 key made by your browser’s Web Crypto. It signs two messages, recovers the key, forges a signature on a third message, and asks Web Crypto whether the forgery is valid. Untick the box to give each signature its own nonce, and watch the same algebra produce garbage.

ECDSA nonce reuse on real P-256 keys. Signing and the attack run in BigInt; Web Crypto checks every signature.

Ed25519: nonces from a hash#

In 2011, Daniel J. Bernstein, Niels Duif, Tanja Lange, Peter Schwabe, and Bo-Yin Yang published Ed25519, a signature scheme designed to remove ECDSA’s sharp edges. It uses Curve25519, a curve Bernstein had published in 2006, written in a different shape: a twisted Edwards curve, −x² + y² = 1 + d·x²·y², modulo the prime 2255 − 19 (hence the name). Two design decisions matter most:

  • The nonce is a hash, not a random number. When the key is created, a SHA-512 of the 32-byte secret seed is split in two: half becomes the private scalar a, the other half a secret prefix. Each signature’s nonce is r = SHA-512(prefix ‖ message). It’s unpredictable to anyone without the prefix, different for each message, and needs no random number generator at signing time. The PS3 bug can’t happen.
  • The addition formula has no special cases. On an Edwards curve, the same formula adds any two points, including a point to itself, and the identity is an ordinary point, (0, 1). There’s no point at infinity and no separate doubling formula, which removes whole classes of implementation bugs and makes constant-time code easier.

Here’s Ed25519 signing from scratch, in about 40 lines, compared with Node’s, using the first test vector from RFC 8032:

ed25519.mjs
// ed25519.mjs: Ed25519 signing from scratch (RFC 8032), byte for byte the same as Node's. Note where the nonce
// comes from: a hash of a secret and the message, so it can never repeat across messages, and needs no randomness.
import { createHash, createPrivateKey, createPublicKey, sign } from "node:crypto";

const p = 2n ** 255n - 19n;
const L = 2n ** 252n + 27742317777372353535851937790883648493n; // the order of the base point
const mod = (x, m = p) => ((x % m) + m) % m;
const pow = (x, e, m = p) => { let r = 1n; x = mod(x, m); for (; e > 0n; e >>= 1n, x = (x * x) % m) if (e & 1n) r = (r * x) % m; return r; };
const inv = (x) => pow(x, p - 2n); // Fermat: x^(p−2) = x⁻¹ mod a prime
const d = mod(-121665n * inv(121666n));

// The curve is −x² + y² = 1 + d·x²·y² (twisted Edwards). Its addition law has no special cases: no infinity,
// no separate doubling formula. That's part of why Ed25519 is easy to implement safely.
const add = ([x1, y1], [x2, y2]) => {
  const t = mod(d * x1 * x2 * y1 * y2);
  return [mod((x1 * y2 + y1 * x2) * inv(1n + t)), mod((y1 * y2 + x1 * x2) * inv(1n - t))];
};
const mul = (k, P) => { let R = [0n, 1n]; for (; k > 0n; k >>= 1n, P = add(P, P)) if (k & 1n) R = add(R, P); return R; };

// The base point B has y = 4/5 and an even x.
function xFromY(y) {
  const x2 = mod((y * y - 1n) * inv(d * y * y + 1n));
  let x = pow(x2, (p + 3n) / 8n);
  if (mod(x * x - x2) !== 0n) x = mod(x * pow(2n, (p - 1n) / 4n));
  return x & 1n ? p - x : x;
}
const By = mod(4n * inv(5n));
const B = [xFromY(By), By];

const le = (buf) => [...buf].reduceRight((acc, byte) => (acc << 8n) | BigInt(byte), 0n); // little-endian bytes → number
const bytes32 = (x) => Buffer.from(x.toString(16).padStart(64, "0"), "hex").reverse();
const encode = ([x, y]) => bytes32(y | ((x & 1n) << 255n)); // 32 bytes: y, plus the sign of x in the top bit
const sha512 = (...parts) => createHash("sha512").update(Buffer.concat(parts)).digest();

export function ed25519Sign(seed, msg) {
  const h = sha512(seed);
  const scalar = Buffer.from(h.subarray(0, 32));
  scalar[0] &= 248; scalar[31] &= 127; scalar[31] |= 64; // "clamping"
  const a = le(scalar), prefix = h.subarray(32), A = encode(mul(a, B));
  const r = mod(le(sha512(prefix, msg)), L); // THE NONCE: secret prefix + message, hashed
  const R = encode(mul(r, B));
  const k = mod(le(sha512(R, A, msg)), L);
  const S = mod(r + k * a, L);
  return { publicKey: A, signature: Buffer.concat([R, bytes32(S)]) };
}

if (process.argv[1]?.endsWith("ed25519.mjs")) {
  const seed = Buffer.from("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "hex"); // RFC 8032, test 1
  const nodeKey = createPrivateKey({ key: Buffer.concat([Buffer.from("302e020100300506032b657004220420", "hex"), seed]), format: "der", type: "pkcs8" });
  for (const text of ["", "hello", "hello"]) {
    const msg = Buffer.from(text);
    const ours = ed25519Sign(seed, msg);
    const nodes = sign(null, msg, nodeKey);
    console.log(JSON.stringify(text).padEnd(8), ours.signature.toString("hex").slice(0, 32) + "…", "same as Node:", ours.signature.equals(nodes));
  }
  const nodePub = createPublicKey(nodeKey).export({ format: "der", type: "spki" }).subarray(-32);
  console.log("public key", ed25519Sign(seed, Buffer.alloc(0)).publicKey.toString("hex"), "same as Node:", nodePub.equals(ed25519Sign(seed, Buffer.alloc(0)).publicKey));
}
""       e5564300c360ac729086e2cc806e828a… same as Node: true
"hello"  511ca497c4d4270b098b1afd5ae4e3b9… same as Node: true
"hello"  511ca497c4d4270b098b1afd5ae4e3b9… same as Node: true
public key d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a same as Node: true

The empty-message signature and the public key are exactly the values printed in RFC 8032, and the test checks ten more random keys and messages against Node byte for byte. Signing “hello” twice produces the same signature, by design: same message, same nonce, same result, which reveals nothing new. A different message gets a different nonce, because the nonce is a hash of the message; two messages sharing a nonce would require a SHA-512 collision.

Deterministic nonces aren’t exclusive to Ed25519. RFC 6979 (2013) describes deterministic ECDSA, which derives k from the private key and the message with HMAC, and many libraries use it, including most Bitcoin software. Deterministic signing has one known weakness of its own: an attacker who can physically glitch a device while it signs the same message twice may get a faulty signature that leaks the key. Some implementations therefore mix fresh randomness into the deterministic nonce (“hedged” signatures), which keeps the protection against bad random number generators.

ES256 and Ed25519 in JWTs#

In a JWT, the algorithm is named in the header. ES256 is ECDSA with P-256 and SHA-256 (RFC 7518). Ed25519 was first registered under the name EdDSA (RFC 8037), which didn’t say which curve; RFC 9864 (October 2025) deprecated it in favor of the fully specified Ed25519. Here are both, plus RS256 for comparison, each signing the same claims twice with jose:

tokens.mjs
// tokens.mjs: ES256 and Ed25519 JWTs with jose. Same claims, signed twice with each algorithm.
import { SignJWT, generateKeyPair, jwtVerify } from "jose";

const claims = { sub: "user-8231", scope: "read" };
for (const alg of ["ES256", "Ed25519", "RS256"]) {
  const { privateKey, publicKey } = await generateKeyPair(alg, { extractable: true });
  const sign = () => new SignJWT(claims).setProtectedHeader({ alg }).setIssuedAt(1794182400).sign(privateKey);
  const [t1, t2] = [await sign(), await sign()];
  await jwtVerify(t1, publicKey);
  await jwtVerify(t2, publicKey);
  const signature = t1.split(".")[2];
  console.log(`${alg.padEnd(8)} signature ${Buffer.from(signature, "base64url").length} bytes (${signature.length} chars), token ${t1.length} chars, signed twice: ${t1 === t2 ? "identical" : "different"}`);
}
ES256    signature 64 bytes (86 chars), token 176 chars, signed twice: different
Ed25519  signature 64 bytes (86 chars), token 179 chars, signed twice: identical
RS256    signature 256 bytes (342 chars), token 432 chars, signed twice: identical

ES256 produces a different token each time, because each signature uses a new random nonce. Ed25519 and RS256 are deterministic. Both curve signatures are 64 bytes, 86 characters of base64url, against 342 for RS256. In a JWS, ES256’s signature is the raw r ‖ s, not the DER encoding most libraries produce by default, a classic source of “invalid signature” bugs that the JWS article covers. Their public keys look like this as JWKs:

{ "kty": "EC",  "crv": "P-256",   "x": "<32 bytes, base64url>", "y": "<32 bytes, base64url>" }
{ "kty": "OKP", "crv": "Ed25519", "x": "<32 bytes, base64url>" }

A P-256 public key is a point, so it has both coordinates. An Ed25519 public key is a single 32-byte value: the point’s y-coordinate, plus one bit saying which of the two possible x values it is. For how tokens are verified and what to check besides the signature, see the JWT architecture guide; for using these keys to authenticate a client instead of a shared secret, see Private Key JWT. Elliptic curves also do key agreement: JWE’s ECDH-ES (in the JWE article) and TLS 1.3’s X25519 (in the TLS article) use the same d·G arithmetic to agree on a shared secret.

Sizes and speed#

bench.mjs
// bench.mjs: key and signature sizes, and signing and verifying speed, with Node's built-in crypto.
import { generateKeyPairSync, sign, verify } from "node:crypto";

const kinds = {
  "ES256 (P-256)": { type: "ec", opts: { namedCurve: "P-256" }, hash: "sha256", enc: { dsaEncoding: "ieee-p1363" } },
  "Ed25519": { type: "ed25519", opts: {}, hash: null, enc: {} },
  "RS256 (RSA-2048)": { type: "rsa", opts: { modulusLength: 2048 }, hash: "sha256", enc: {} },
  "RS256 (RSA-3072)": { type: "rsa", opts: { modulusLength: 3072 }, hash: "sha256", enc: {} },
};
const msg = Buffer.from("x".repeat(200));
const perSecond = (fn, ms = 400) => { let n = 0; const end = performance.now() + ms; while (performance.now() < end) { fn(); n++; } return Math.round((n * 1000) / ms); };

for (const [name, k] of Object.entries(kinds)) {
  const { privateKey, publicKey } = generateKeyPairSync(k.type, k.opts);
  const key = { key: privateKey, ...k.enc }, pub = { key: publicKey, ...k.enc };
  const sig = sign(k.hash, msg, key);
  const spki = publicKey.export({ format: "der", type: "spki" }).length;
  const keygen = perSecond(() => generateKeyPairSync(k.type, k.opts), k.type === "rsa" ? 1500 : 400);
  console.log(
    `${name.padEnd(17)} public key ${String(spki).padStart(3)} B (SPKI)  signature ${String(sig.length).padStart(3)} B  ` +
    `sign ${String(perSecond(() => sign(k.hash, msg, key))).padStart(6)}/s  verify ${String(perSecond(() => verify(k.hash, msg, pub, sig))).padStart(6)}/s  keygen ${String(keygen).padStart(6)}/s`,
  );
}
AlgorithmPublic key (SPKI)SignatureSignVerifyNew key
ES256 (P-256)91 B64 B47,970/s19,075/s47,623/s
Ed2551944 B64 B44,688/s15,660/s43,785/s
RS256 (RSA-2048)294 B256 B2,743/s63,808/s43/s
RS256 (RSA-3072)422 B384 B903/s35,933/s7/s

Measured with Node 24 (OpenSSL 3.5) on one machine, in a Docker container, so treat the speeds as relative. The pattern is the useful part. Elliptic curves sign more than 15 times faster than RSA-2048 and generate keys about a thousand times faster, with keys and signatures a fraction of the size, at a higher security level (RSA-3072 is the like-for-like comparison). RSA verifies faster, thanks to its tiny public exponent, which can matter for a service that only verifies. ES256 and Ed25519 are close: OpenSSL’s P-256 code is heavily optimized for common processors, and on this machine it was slightly faster. Ed25519’s advantages are safety, simplicity, and the smaller key, not raw speed.

Which should you use?#

  • New systems you control: Ed25519. Deterministic nonces, no special cases, small keys, and wide library support (OpenSSL, Web Crypto in current browsers, Node, Go, Java 15+, .NET via libraries). It’s approved in FIPS 186-5 (2023).
  • When you need NIST P-256: ES256. Some compliance regimes, hardware security modules, smart cards, and passkey authenticators only offer NIST curves. ES256 is fine when the library is well tested; never implement the nonce yourself, and prefer libraries that use RFC 6979 or hedged nonces.
  • RS256 for compatibility with old verifiers, with at least a 2048-bit key (3072 for anything long-lived). Its fast verification is sometimes a reason too.
  • Don’t roll your own curve code for production. The from-scratch code here is for understanding; it isn’t constant-time and doesn’t validate inputs (for example, checking that a received public key is actually on the curve, the cause of “invalid curve” attacks).

Timeline#

YearWhat happened
1985Neal Koblitz and Victor Miller independently propose elliptic-curve cryptography
1991NIST proposes DSA, the algorithm ECDSA is modeled on
1999–2000ECDSA standardized (ANSI X9.62); NIST’s P-256 and other curves published in FIPS 186-2
2006Daniel J. Bernstein publishes Curve25519
2009Bitcoin launches, signing with ECDSA on secp256k1
2010fail0verflow shows the PS3’s reused ECDSA nonce at 27C3
2011Ed25519 published
2013RFC 6979, deterministic ECDSA; an Android random number bug leaks Bitcoin keys
2015RFC 7518 defines ES256 for JOSE
2016–17RFC 7748 (X25519) and RFC 8032 (EdDSA); RFC 8037 brings Ed25519 to JOSE
2018TLS 1.3 makes elliptic-curve key agreement the norm
2019TPM-Fail and Minerva recover keys from small timing leaks of ECDSA nonces
2023FIPS 186-5 approves EdDSA
2025RFC 9864 replaces the JOSE name EdDSA with Ed25519

FAQ#

What’s the difference between ES256, ECDSA, and P-256?

P-256 is the curve. ECDSA is the signature algorithm. ES256 is the JOSE name for ECDSA on P-256 with SHA-256, in the raw 64-byte signature format. ES384 and ES512 use P-384 and P-521.

Is Ed25519 the same as EdDSA?

EdDSA is the family; Ed25519 is EdDSA on Curve25519 with SHA-512, and Ed448 is the larger sibling. In JOSE, EdDSA used to cover both, with the curve in the key; it’s now deprecated in favor of Ed25519 and Ed448.

Can I reuse my RSA knowledge?

Mostly. The arithmetic is the same modular arithmetic, inverses come from the same extended Euclidean algorithm, and double-and-add is square-and-multiply in new clothes. What changes is the hard problem (discrete logarithms on a curve instead of factoring) and the key sizes.

Are the NIST curves backdoored?

There’s no evidence that P-256 is weak, and it has been studied intensively for over 25 years. Suspicion grew after 2013, when the Dual_EC_DRBG random number generator was shown to be very likely backdoored, and because the NIST curves were generated from seeds whose origin was never explained. Curve25519’s parameters were chosen by published, simple rules, which is one reason many people prefer it.

Will quantum computers break this?

A large enough quantum computer running Shor’s algorithm would break elliptic curves (and RSA). None exists today, but the replacements are already standardized: NIST published ML-DSA, a post-quantum signature scheme, in FIPS 204 (2024). Elliptic curves remain the right choice for now; plan for the switch in systems that must stay secure for decades.

Why is my ES256 signature 70-something bytes in Java or OpenSSL?

That’s DER, an encoding of (r, s) with length and type bytes around each number. JWS wants the raw 64 bytes. Convert, or ask the library for the raw (“P1363”) form, as the examples here do with Node’s dsaEncoding: "ieee-p1363".

Try it in your browser