Skip to content

WireGuard Key Generator — Python 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 Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""wireguard-keygen — WireGuard key generation (Curve25519 / RFC 7748 X25519).

Language: Python 3 (standard library only).
CosmoDev polyglot showcase port of the `wireguard-keygen` tool, ported from
src/lib/wireguard-keygen.ts (the canonical TypeScript implementation).

Python integers are arbitrary precision, so the BigInt Montgomery ladder
translates one line at a time. Randomness comes from ``secrets.token_bytes``
(the stdlib CSPRNG — the stand-in for Web Crypto's ``getRandomValues``) and
keys serialize as standard padded Base64 (44 chars for 32 bytes) via the
``base64`` module, exactly the format WireGuard config files expect.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import base64
import secrets

# Length of every WireGuard key, in bytes.
KEY_LENGTH = 32

# Curve25519 domain parameters: y^2 = x^3 + 486662x^2 + x over GF(2^255 - 19).
P = (1 << 255) - 19
A24 = 121_665  # (486662 - 2) / 4

BASE_POINT = b"\x09" + bytes(KEY_LENGTH - 1)  # u = 9, little-endian


# ---------------------------------------------------------------------------
# Base64 codec (standard alphabet, always padded — the WireGuard format)
# ---------------------------------------------------------------------------

def bytes_to_base64(raw: bytes) -> str:
    """Encode bytes as standard Base64 with ``=`` padding (32 bytes → 44 chars)."""
    return base64.b64encode(raw).decode("ascii")


def base64_to_bytes(b64: str) -> bytes:
    """Decode standard Base64 (with padding). Raises on invalid input.

    ``validate=True`` rejects characters outside the Base64 alphabet instead
    of silently dropping them; malformed lengths/padding raise too, matching
    the TypeScript port's "throw on invalid input" contract.
    """
    return base64.b64decode(b64.strip(), validate=True)


# ---------------------------------------------------------------------------
# Curve25519 scalar multiplication (RFC 7748 Montgomery ladder)
# ---------------------------------------------------------------------------

def clamp_private_key(key: bytes) -> bytes:
    """Clamp 32 bytes into a valid Curve25519 scalar (RFC 7748 §5). Returns a copy."""
    if len(key) != KEY_LENGTH:
        raise ValueError(f"Private key must be {KEY_LENGTH} bytes, got {len(key)}")
    out = bytearray(key)
    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 bytes(out)


def curve25519(scalar: bytes, u: bytes) -> bytes:
    """X25519 scalar multiplication ``scalar · u`` — the RFC 7748 Montgomery ladder.

    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).
    """
    if len(scalar) != KEY_LENGTH:
        raise ValueError(f"Scalar must be {KEY_LENGTH} bytes, got {len(scalar)}")
    if len(u) != KEY_LENGTH:
        raise ValueError(f"u-coordinate must be {KEY_LENGTH} bytes, got {len(u)}")
    k = int.from_bytes(clamp_private_key(scalar), "little")
    # Mask the most significant bit of the u-coordinate per RFC 7748 §5.
    x1 = int.from_bytes(u, "little") & ((1 << 255) - 1)

    x2, z2, x3, z3, swap = 1, 0, x1, 1, 0
    for t in range(254, -1, -1):
        bit = (k >> t) & 1
        swap ^= bit
        if swap == 1:
            x2, x3 = x3, x2
            z2, z3 = z3, z2
        swap = bit

        a = (x2 + z2) % P
        aa = (a * a) % P
        b = (x2 - z2) % P  # Python's % is already in the canonical range [0, P)
        bb = (b * b) % P
        e = (aa - bb) % P
        c = (x3 + z3) % P
        d = (x3 - z3) % P
        da = (d * a) % P
        cb = (c * b) % P
        x3 = ((da + cb) % P) ** 2 % P
        z3 = x1 * ((da - cb) % P) ** 2 % P
        x2 = aa * bb % P
        z2 = e * ((aa + A24 * e) % P) % P
    # 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 (x2 * pow(z2, P - 2, P) % P).to_bytes(KEY_LENGTH, "little")


# ---------------------------------------------------------------------------
# Key generation
# ---------------------------------------------------------------------------

def generate_private_key() -> str:
    """A fresh private key: 32 CSPRNG bytes, clamped, Base64."""
    return bytes_to_base64(clamp_private_key(secrets.token_bytes(KEY_LENGTH)))


def generate_preshared_key() -> str:
    """A fresh pre-shared key: 32 CSPRNG bytes, Base64 — used as-is, never clamped."""
    return bytes_to_base64(secrets.token_bytes(KEY_LENGTH))


def private_key_to_public(private_key_base64: str) -> str:
    """Derive the WireGuard public key that pairs with a Base64 private key."""
    priv = base64_to_bytes(private_key_base64)
    if len(priv) != KEY_LENGTH:
        raise ValueError(f"Invalid private key: expected {KEY_LENGTH} bytes, got {len(priv)}")
    return bytes_to_base64(curve25519(priv, BASE_POINT))


def generate_wireguard_keys() -> dict[str, str]:
    """A fresh WireGuard key pair (private + matching public key, both Base64)."""
    private_key = generate_private_key()
    return {"private_key": private_key, "public_key": private_key_to_public(private_key)}


# ---------------------------------------------------------------------------
# Config template
# ---------------------------------------------------------------------------

def format_config(keys: dict[str, str], psk: str | None = None) -> str:
    """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).
    """
    lines = [
        "[Interface]",
        "# Your side — keep PrivateKey secret, share PublicKey with the peer",
        f"PrivateKey = {keys['private_key']}",
        f"PublicKey = {keys['public_key']}",
        "# 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:
        lines += [
            "# Optional pre-shared key — the same value must be set on BOTH sides",
            f"PresharedKey = {psk}",
        ]
    lines += [
        "# 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 "\n".join(lines)

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 →