WireGuard Key Generator — JavaScript source
Generate Curve25519 key pairs for WireGuard VPN configuration. Derives the public key from a clamped private key with a pure-BigInt RFC 7748 Montgomery ladder, optionally generates a pre-shared key, and renders a ready-to-edit wg-quick config template. Everything runs 100% client-side - keys never leave your browser.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* wireguard-keygen — WireGuard key generation (Curve25519 / RFC 7748 X25519).
*
* Language: JavaScript (ES module; runs in browsers, Node >= 16, Bun, Deno).
* CosmoDev polyglot showcase port of the `wireguard-keygen` tool, ported from
* src/lib/wireguard-keygen.ts.
*
* This is the easiest port in the showcase: JavaScript's BigInt maps 1:1 onto
* the reference's BigInt Montgomery ladder, and `crypto.getRandomValues` is
* the very same Web Crypto CSPRNG — so the files differ only by type
* annotations. Every key serializes as standard padded Base64 (44 chars for
* 32 bytes), exactly what WireGuard config files expect.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
/** Length of every WireGuard key, in bytes. */
export const KEY_LENGTH = 32;
// Curve25519 domain parameters: y^2 = x^3 + 486662x^2 + x over GF(2^255 - 19).
const P = (1n << 255n) - 19n;
const A24 = 121665n; // (486662 - 2) / 4
const BASE_POINT = new Uint8Array(KEY_LENGTH); // u = 9, little-endian
BASE_POINT[0] = 9;
// ---------------------------------------------------------------------------
// Base64 codec (standard alphabet, always padded — the WireGuard format)
// ---------------------------------------------------------------------------
/** Encode bytes as standard Base64 with `=` padding (32 bytes → 44 chars). */
export function bytesToBase64(bytes) {
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary);
}
/** Decode standard Base64 (with padding). Throws on invalid input. */
export function base64ToBytes(b64) {
const binary = atob(b64.trim()); // throws on bad length/characters
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
return out;
}
// ---------------------------------------------------------------------------
// Curve25519 scalar multiplication (RFC 7748 Montgomery ladder)
// ---------------------------------------------------------------------------
/** Reduce `a` into the canonical range [0, P). */
function mod(a) {
const r = a % P;
return r >= 0n ? r : r + P;
}
/** `base^exponent mod P` via square-and-multiply (used for field inversion). */
function powMod(base, exponent) {
let result = 1n;
let b = mod(base);
let e = exponent;
while (e > 0n) {
if (e & 1n) result = mod(result * b);
b = mod(b * b);
e >>= 1n;
}
return result;
}
/** Clamp 32 bytes into a valid Curve25519 scalar (RFC 7748 §5). Returns a copy. */
export function clampPrivateKey(key) {
if (key.length !== KEY_LENGTH) {
throw new Error(`Private key must be ${KEY_LENGTH} bytes, got ${key.length}`);
}
const out = key.slice();
out[0] &= 248; // clear the low 3 bits → multiple of the cofactor
out[31] &= 127; // clear the high bit
out[31] |= 64; // force bit 254 → the ladder always sees a 255-bit scalar
return out;
}
function decodeLittleEndian(bytes) {
let n = 0n;
for (let i = bytes.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(bytes[i]);
return n;
}
function encodeLittleEndian(n, length = KEY_LENGTH) {
const out = new Uint8Array(length);
for (let i = 0; i < length; i++) {
out[i] = Number(n & 0xffn);
n >>= 8n;
}
return out;
}
/**
* X25519 scalar multiplication `scalar · u` — the RFC 7748 Montgomery ladder
* in plain BigInt arithmetic. Deterministic and dependency-free. The scalar is
* clamped internally (an unclamped input yields the same result as its clamped
* form, exactly like every X25519 implementation).
*/
export function curve25519(scalar, u) {
if (scalar.length !== KEY_LENGTH) {
throw new Error(`Scalar must be ${KEY_LENGTH} bytes, got ${scalar.length}`);
}
if (u.length !== KEY_LENGTH) {
throw new Error(`u-coordinate must be ${KEY_LENGTH} bytes, got ${u.length}`);
}
const k = decodeLittleEndian(clampPrivateKey(scalar));
// Mask the most significant bit of the u-coordinate per RFC 7748 §5.
const x1 = decodeLittleEndian(u) & ((1n << 255n) - 1n);
let x2 = 1n;
let z2 = 0n;
let x3 = x1;
let z3 = 1n;
let swap = 0n;
for (let t = 254; t >= 0; t--) {
const bit = (k >> BigInt(t)) & 1n;
swap ^= bit;
if (swap === 1n) {
[x2, x3] = [x3, x2];
[z2, z3] = [z3, z2];
}
swap = bit;
const a = mod(x2 + z2);
const aa = mod(a * a);
const b = mod(x2 - z2);
const bb = mod(b * b);
const e = mod(aa - bb);
const c = mod(x3 + z3);
const d = mod(x3 - z3);
const da = mod(d * a);
const cb = mod(c * b);
const sum = mod(da + cb);
const diff = mod(da - cb);
x3 = mod(sum * sum);
z3 = mod(x1 * mod(diff * diff));
x2 = mod(aa * bb);
z2 = mod(e * mod(aa + A24 * e));
}
// No final cswap: the loop leaves swap = k_0, and clamping clears bit 0,
// so swap is provably 0 here for every input this function accepts.
// x2 / z2 via z2^(P-2) (Fermat): the affine u-coordinate result.
return encodeLittleEndian(mod(x2 * powMod(z2, P - 2n)));
}
// ---------------------------------------------------------------------------
// Key generation
// ---------------------------------------------------------------------------
function randomBytes(length) {
const bytes = new Uint8Array(length);
globalThis.crypto.getRandomValues(bytes);
return bytes;
}
/** A fresh private key: 32 CSPRNG bytes, clamped, Base64. */
export function generatePrivateKey() {
return bytesToBase64(clampPrivateKey(randomBytes(KEY_LENGTH)));
}
/** A fresh pre-shared key: 32 CSPRNG bytes, Base64 — used as-is, never clamped. */
export function generatePresharedKey() {
return bytesToBase64(randomBytes(KEY_LENGTH));
}
/**
* Derive the WireGuard public key that pairs with a Base64 private key
* (Curve25519 scalar multiplication of the base point). Async so a WebCrypto
* X25519 backend could drop in without touching callers.
*/
export async function privateKeyToPublic(privateKeyBase64) {
const priv = base64ToBytes(privateKeyBase64);
if (priv.length !== KEY_LENGTH) {
throw new Error(`Invalid private key: expected ${KEY_LENGTH} bytes, got ${priv.length}`);
}
return bytesToBase64(curve25519(priv, BASE_POINT));
}
/** A fresh WireGuard key pair (private + matching public key, both Base64). */
export async function generateWireGuardKeys() {
const privateKey = generatePrivateKey();
const publicKey = await privateKeyToPublic(privateKey);
return { privateKey, publicKey };
}
// ---------------------------------------------------------------------------
// Config template
// ---------------------------------------------------------------------------
/**
* Render a `wg-quick` config template around a key pair. The peer's public
* key, endpoint, and your tunnel address depend on the other side, so they
* stay as placeholders. A `PresharedKey` line is included only when `psk` is
* given (it must be present on BOTH sides of the tunnel).
*/
export function formatConfig(keys, psk) {
const lines = [
'[Interface]',
'# Your side — keep PrivateKey secret, share PublicKey with the peer',
`PrivateKey = ${keys.privateKey}`,
`PublicKey = ${keys.publicKey}`,
'# Tunnel address assigned by your server (plus optional tunnel DNS)',
'Address = 10.0.0.2/32',
'# DNS = 1.1.1.1',
'',
'[Peer]',
"# The other side's public key",
'PublicKey = <PEER_PUBLIC_KEY>',
];
if (psk !== undefined && psk !== '') {
lines.push(
'# Optional pre-shared key — the same value must be set on BOTH sides',
`PresharedKey = ${psk}`,
);
}
lines.push(
'# Route everything through the tunnel (or scope it, e.g. 10.0.0.0/24)',
'AllowedIPs = 0.0.0.0/0, ::/0',
"# The peer's public address and port",
'Endpoint = vpn.example.com:51820',
'PersistentKeepalive = 25',
);
return lines.join('\n');
}
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 →