x25519 - xero/leviathan-crypto GitHub Wiki
X25519: Curve25519 Diffie-Hellman
Classical Diffie-Hellman key agreement via X25519 (RFC 7748, Elliptic Curves for Security), the Curve25519 instance built on the Montgomery ladder over GF(2^255-19). 32-byte secrets, 32-byte public keys, 32-byte shared u-coordinate output. The TypeScript layer rejects degenerate all-zero shared secrets per RFC 7748 §6.1, Curve25519, contributory-behaviour discussion.
Table of Contents
Overview
X25519 is the Curve25519 instance of Diffie-Hellman defined by RFC 7748 §5, The X25519 and X448 Functions. The function takes a 32-byte secret scalar and a 32-byte u-coordinate public key and returns a 32-byte shared u-coordinate. Two parties compute the same shared u-coordinate by exchanging public keys and running X25519 against each other's pk under their own sk.
Two operations ship:
keygen/keygenDerand, RFC 7748 §6, Diffie-Hellman. Computepk = X25519(clamp(sk), 9)against the Curve25519 basepoint u = 9.dh, RFC 7748 §6. Computeshared = X25519(clamp(sk), peerPk)against a peer's public key.
Per RFC 7748 §5, The X25519 and X448 Functions, the function clamps the input scalar on every call: the low 3 bits clear, bit 254 sets, and bit 255 clears. Callers pass the secret as "any 32 random bytes" and the WASM applies clamping internally. The library never stores a pre-clamped form; round-tripping a key through external storage preserves the original 32 random bytes byte-for-byte.
The shared secret carries contributory entropy from both parties
when both public keys are non-small-order points. RFC 7748 §6.1
discusses the small-order pk case: if the peer's public key has
order dividing 8, the Montgomery ladder produces the identity
point, encoded as all-zero bytes. That output carries no
contributory entropy from the local secret and must be rejected.
The TypeScript layer enforces this in X25519.dh via a
constant-time all-zero scan; see All-Zero
Rejection for the rationale and the
constant-time discipline.
The test corpus pairs RFC 7748 §6.1, Curve25519, Alice and Bob vectors with the iter=1 and iter=1000 chain records from RFC 7748 §5, The X25519 and X448 Functions. The 1000-iteration record exercises the same scalar arithmetic and ladder loop under repeated composition; the 1,000,000-iteration record is out of scope for the CI suite (runtime budget) and is deferred to manual verification per vector_audit.md.
Init
import { init } from 'leviathan-crypto'
import { x25519Wasm } from 'leviathan-crypto/x25519/embedded'
await init({ x25519: x25519Wasm })
The leviathan-crypto/x25519/embedded subpath exports the WASM
blob under three names that all resolve to the same string:
x25519Wasm (reads most naturally in this context),
curve25519Wasm (the canonical name shared with the
leviathan-crypto/ed25519/embedded subpath), and ed25519Wasm
(the alias preferred under the matching subpath). Pick whichever
matches the surrounding code; tree-shaking is unaffected.
Ed25519 and X25519 share a single WASM binary, curve25519.wasm,
which hosts the GF(2^255-19) field arithmetic, the Montgomery
ladder, the edwards25519 substrate, the scalar arithmetic mod L,
plus an embedded SHA-512. The top-level init() accepts
ed25519 and x25519 as aliases that resolve to the underlying
curve25519 module. Calling either alias enables both classes,
and passing both aliases with the same source is de-duped at the
init layer; passing different sources for the two aliases
throws.
For tree-shakeable imports the leviathan-crypto/x25519 subpath
exports its own init function:
import { x25519Init } from 'leviathan-crypto/x25519'
import { x25519Wasm } from 'leviathan-crypto/x25519/embedded'
await x25519Init(x25519Wasm)
x25519Init(source) and ed25519Init(source) both load the
same WASM module under the curve25519 slot. X25519 ships
scalar (no WebAssembly SIMD); init({ x25519: ... }) works on
every WASM-capable runtime regardless of SIMD support.
X25519 API
Construction is parameter-less. Every public method runs against
the singleton curve25519 instance, stages inputs at fixed
offsets above the WASM mutable region, calls the underlying
export, copies outputs to fresh Uint8Arrays, then wipes the
staged buffers.
Constructor
new X25519()
Throws if init({ x25519: ... }) (or init({ ed25519: ... }),
or the subpath init) has not been called.
keygen()
Generate a new key pair using a fresh 32-byte secret from
crypto.getRandomValues. Equivalent to calling keygenDerand
with a random sk; the local sk buffer is wiped on return.
const dh = new X25519()
const { publicKey, secretKey } = dh.keygen()
// publicKey: 32-byte public u-coordinate (RFC 7748 §6,
// Diffie-Hellman)
// secretKey: 32-byte secret (RFC 7748 §5, The X25519 and X448
// Functions, opaque random bytes)
dh.dispose()
keygenDerand(sk)
Deterministic key generation from a 32-byte secret, RFC 7748 §6.
The substrate clamps internally on every call; the returned
secretKey is a fresh copy of sk (NOT pre-clamped).
const sk = new Uint8Array(32)
crypto.getRandomValues(sk)
const dh = new X25519()
const { publicKey, secretKey } = dh.keygenDerand(sk)
dh.dispose()
sk.fill(0)
The public key is pk = X25519(clamp(sk), 9) where 9 is the
Curve25519 basepoint u-coordinate (RFC 7748 §4.1, Curve25519).
Throws RangeError if sk.length !== 32.
dh(sk, peerPk)
X25519 Diffie-Hellman, RFC 7748 §6. Returns the 32-byte shared u-coordinate.
const shared = dh.dh(secretKey, peerPublicKey)
Internally:
- The substrate clamps
skto a fresh scratch slot. The caller'sskbuffer is read once and never mutated. - The Montgomery ladder runs against
peerPkwith the clamped scalar. The substrate'sfeFromBytesmasks bit 255 ofpeerPkinternally per RFC 7748 §5, The X25519 and X448 Functions; callers do NOT pre-mask. - The TypeScript wrapper accumulates an OR-scan across the 32
output bytes in constant time. If the accumulator is zero,
the wrapper wipes the shared buffer and throws
KeyAgreementError.
The all-zero scan is structurally constant-time. The loop runs for a fixed 32 iterations with no early exit on the first non-zero byte; the branch only fires AFTER the full accumulator is known. See All-Zero Rejection for the threat model.
dispose()
Wipe all curve25519 WASM scratch memory. Idempotent. Safe to
call multiple times. Every public method already wipes the
WASM mutable region and the TS-side staging region on success
and throw paths; dispose() is defence-in-depth at instance
teardown.
Validation Behavior
X25519 distinguishes two failure classes: caller-contract
violations (throw TypeError or RangeError) and a single
cryptographic failure mode (small-order peer pk producing an
all-zero shared secret, throws KeyAgreementError).
| Condition | keygen / keygenDerand |
dh |
|---|---|---|
Input not a Uint8Array |
throw TypeError |
throw TypeError |
sk.length !== 32 |
throw RangeError |
throw RangeError |
peerPk.length !== 32 |
n/a | throw RangeError |
| Peer pk produces all-zero shared secret | n/a | throw KeyAgreementError |
The peer pk is otherwise treated as opaque public data. The
substrate masks bit 255 internally; non-canonical encodings with
u >= p pass through (RFC 7748 §5, The X25519 and X448
Functions, accepts that posture). No on-curve check runs on the
peer pk; Curve25519's twist security covers the non-curve case.
The strict all-zero rejection is a TypeScript-layer check rather than a WASM-layer check. The WASM unconditionally writes the shared u-coordinate to the caller's slot regardless of whether it is all-zero; the TS layer then rejects. This matches the x25519-dalek posture and preserves WASM-vs-oracle byte agreement on any test record that exercises a small-order peer pk. See All-Zero Rejection.
Key Format
Secret key sk, RFC 7748 §5, The X25519 and X448 Functions:
sk = 32 random bytes (opaque, NOT pre-clamped)
The substrate clamps the scalar on every call:
clamped[0] = sk[0] & 0xF8 // clear low 3 bits
clamped[31] = (sk[31] & 0x7F) | 0x40 // clear bit 255, set bit 254
The returned secretKey from keygen / keygenDerand is the
unclamped form, so round-tripping a key through external
storage preserves byte-equality.
Public key pk, RFC 7748 §5, The X25519 and X448 Functions:
pk = 32 bytes (encoded u-coordinate, little-endian)
The substrate masks bit 255 of the encoded u-coord internally per RFC 7748 §5; callers pass the encoded bytes byte-for-byte.
Shared secret, RFC 7748 §6, Diffie-Hellman:
shared = 32 bytes (encoded u-coordinate of [clamp(sk)] * peerPk)
The shared secret is itself a 32-byte u-coordinate and should be fed through a KDF (HKDF-SHA-256, HKDF-SHA-512, BLAKE3 derive_key) before use as encryption key material. Treat the raw shared secret as ephemeral.
All-Zero Rejection
The Curve25519 group has a few small-order points whose order divides 8. RFC 7748 §6.1, Curve25519, lists the canonical small-order u-coordinates (0, 1, and a handful of curve and twist points). Running the Montgomery ladder against any small-order peer pk produces a shared u-coordinate of zero: the scalar is annihilated by the small order, leaving the identity. The all-zero output carries no contributory entropy from the local secret.
X25519.dh rejects all-zero outputs with KeyAgreementError.
The rationale follows the contributory-behaviour discussion in
RFC 7748 §6.1: a peer who knowingly submits a small-order pk
can force the shared secret to a constant value the peer
already knows, defeating the security goal of Diffie-Hellman.
The check lives at the TS layer rather than inside the WASM:
- Substrate purity. The WASM substrate computes
X25519(k, u)per RFC 7748 §5, The X25519 and X448 Functions, without filtering. That matches x25519-dalek's WASM-level posture and keeps the substrate's input-output behaviour spec-pure. - Vector compatibility. Any test record that supplies a small-order peer pk and an expected all-zero output verifies byte-for-byte at the WASM boundary. The TS-layer rejection is the public API contract; the WASM-vs-oracle cross-check continues to pass.
- Constant-time discipline at the right layer. The TS scan accumulates 32 byte OR operations into a single 32-bit accumulator. The loop runs the full 32 iterations regardless of whether early bytes are non-zero; the conditional that throws fires only after the accumulator is fully computed. No data-dependent branch reveals which byte was the first non-zero one.
The wipe path on rejection runs before the throw: X25519.dh
zeroes the shared-secret slot in its finally, so the
all-zero buffer that triggered rejection does not linger.
Wipe Discipline
Every X25519 public method ends with a two-phase wipe:
- The WASM-side
wipeBuffersexport zeroes the mutable region fromMUTABLE_STARTtoBUFFER_END. That covers the clamped scalar (X25519_SCALAR_CLAMP), the basepoint u-coordinate (BASEPOINT_U), and the Montgomery ladder scratch (LADDER_TMP). - The TypeScript wrapper zeroes the I/O staging region above
BUFFER_END(the sk slot, pk slot, peer-pk slot, and shared-secret slot). The WASM does not own that region; the wrapper owns it and is responsible for the wipe.
Both phases run inside a try / finally so the wipe fires on
the success path, on a KeyAgreementError throw, and on any
other exception that propagates through the method. Caller-
supplied buffers (sk, peerPk) are NEVER mutated; the library
copies them into the staging region, never aliases them.
The substrate's internal wipeX25519 helper zeroes the
clamped-scalar slot as an additional per-call defence-in-depth
inside the WASM, so a caller that keeps the WASM instance alive
across multiple operations does not leave a stale clamped
scalar between calls.
dispose() re-runs both phases. Calling it multiple times is
safe.
Error Reference
| Error | Cause |
|---|---|
Error: leviathan-crypto: call init({ x25519: ... }) before using X25519 |
Class constructor invoked before init. |
TypeError: leviathan-crypto: x25519 secret key must be a Uint8Array |
keygenDerand or dh passed a non-Uint8Array sk. |
RangeError: leviathan-crypto: x25519 secret key must be 32 bytes (got N) |
keygenDerand or dh passed a wrong-length sk. |
TypeError: leviathan-crypto: x25519 public key must be a Uint8Array |
dh passed a non-Uint8Array peerPk. |
RangeError: leviathan-crypto: x25519 public key must be 32 bytes (got N) |
dh passed a wrong-length peerPk. |
KeyAgreementError: leviathan-crypto: X25519 shared secret is all-zero ... |
Peer pk is a small-order point; shared secret carries no entropy. |
KeyAgreementError extends Error and exists specifically for
this code path; consumers can branch on it via instanceof KeyAgreementError to distinguish a degenerate exchange from a
caller-side contract violation.
Cross-References
| Document | Description |
|---|---|
| architecture | Repository structure, build and CI, WASM modules, public API, test suite, and security posture |
| init.md | init() API and module-loader contract |
| asm_curve25519.md | Low-level WASM module reference |
| x25519_audit.md | X25519 audit checklist |
| ed25519.md | Companion signing primitive sharing the same WASM module |
| exports.md | Full export catalog |