Skip to content

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

<?php
/**
 * wireguard-keygen — WireGuard key generation (Curve25519 / RFC 7748 X25519).
 *
 * Language: PHP 7.4+ (standard library + ext-GMP — PHP's core has no
 *           arbitrary-precision integer, and GMP is PHP's standard bignum
 *           extension, bundled with most distributions)
 * CosmoDev polyglot showcase port of the `wireguard-keygen` tool, ported from
 * src/lib/wireguard-keygen.ts (the canonical TypeScript implementation).
 *
 * The TypeScript reference reaches for BigInt; PHP reaches for GMP — the same
 * substitution the C/C++ ports make with OpenSSL's BIGNUM. Randomness comes
 * from random_bytes (the core CSPRNG), and gmp_powm handles the Fermat
 * field inversion, so the Montgomery ladder below reads as a line-for-line
 * analogue of the reference's BigInt one.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

namespace CosmoDev\WireGuardKeygen;

use InvalidArgumentException;

/** Length of every WireGuard key, in bytes. */
const KEY_LENGTH = 32;

/** Curve25519 field prime: y^2 = x^3 + 486662x^2 + x over GF(2^255 - 19). */
const P = '57896044618658097711785492504343953926634992332820282019728792003956564819949';

/** (486662 - 2) / 4 — the ladder's curve constant. */
const A24 = '121665';

/**
 * Encode bytes as standard Base64 with `=` padding (32 bytes → 44 chars).
 */
function bytes_to_base64(string $bytes): string
{
    return base64_encode($bytes);
}

/**
 * Decode standard Base64 (with padding). Throws on invalid input.
 */
function base64_to_bytes(string $b64): string
{
    $bytes = base64_decode(trim($b64), true); // strict: reject bad chars/length
    if ($bytes === false) {
        throw new InvalidArgumentException('Invalid Base64 input');
    }
    return $bytes;
}

/**
 * Clamp 32 bytes into a valid Curve25519 scalar (RFC 7748 §5). Returns a copy.
 */
function clamp_private_key(string $key): string
{
    if (strlen($key) !== KEY_LENGTH) {
        throw new InvalidArgumentException(
            'Private key must be ' . KEY_LENGTH . " bytes, got " . strlen($key)
        );
    }
    $out = $key;
    $out[0] = chr(ord($out[0]) & 248);  // clear the low 3 bits → multiple of the cofactor
    $out[31] = chr(ord($out[31]) & 127); // clear the high bit
    $out[31] = chr(ord($out[31]) | 64);  // force bit 254 → the ladder sees a 255-bit scalar
    return $out;
}

/** Reduce a GMP number into the canonical range [0, P) — gmp_mod already does. */
function mod(\GMP $n): \GMP
{
    return gmp_mod($n, P); // non-negative for a positive divisor, like the TS `mod`
}

/**
 * X25519 scalar multiplication `scalar · u` — the RFC 7748 Montgomery ladder
 * in GMP arithmetic. Deterministic. The scalar is clamped internally (an
 * unclamped input yields the same result as its clamped form, exactly like
 * every X25519 implementation).
 */
function curve25519(string $scalar, string $u): string
{
    if (strlen($scalar) !== KEY_LENGTH) {
        throw new InvalidArgumentException('Scalar must be ' . KEY_LENGTH . " bytes, got " . strlen($scalar));
    }
    if (strlen($u) !== KEY_LENGTH) {
        throw new InvalidArgumentException('u-coordinate must be ' . KEY_LENGTH . " bytes, got " . strlen($u));
    }
    $k = gmp_import(clamp_private_key($scalar), 1, GMP_LSW_FIRST);
    // Mask the most significant bit of the u-coordinate per RFC 7748 §5.
    $x1 = gmp_and(gmp_import($u, 1, GMP_LSW_FIRST), gmp_sub(gmp_pow(2, 255), 1));

    $x2 = gmp_init(1);
    $z2 = gmp_init(0);
    $x3 = $x1;
    $z3 = gmp_init(1);
    $swap = 0;
    for ($t = 254; $t >= 0; $t--) {
        $bit = gmp_testbit($k, $t) ? 1 : 0;
        $swap ^= $bit;
        if ($swap === 1) {
            [$x2, $x3] = [$x3, $x2];
            [$z2, $z3] = [$z3, $z2];
        }
        $swap = $bit;

        $a = mod(gmp_add($x2, $z2));
        $aa = mod(gmp_mul($a, $a));
        $b = mod(gmp_sub($x2, $z2));
        $bb = mod(gmp_mul($b, $b));
        $e = mod(gmp_sub($aa, $bb));
        $c = mod(gmp_add($x3, $z3));
        $d = mod(gmp_sub($x3, $z3));
        $da = mod(gmp_mul($d, $a));
        $cb = mod(gmp_mul($c, $b));
        $sum = mod(gmp_add($da, $cb));
        $diff = mod(gmp_sub($da, $cb));
        $x3 = mod(gmp_mul($sum, $sum));
        $z3 = mod(gmp_mul($x1, mod(gmp_mul($diff, $diff))));
        $x2 = mod(gmp_mul($aa, $bb));
        $z2 = mod(gmp_mul($e, mod(gmp_add($aa, gmp_mul(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.
    $result = mod(gmp_mul($x2, gmp_powm($z2, gmp_sub(P, 2), P)));
    return str_pad(gmp_export($result, 1, GMP_LSW_FIRST), KEY_LENGTH, "\0");
}

// ---------------------------------------------------------------------------
// Key generation
// ---------------------------------------------------------------------------

/** A fresh private key: 32 CSPRNG bytes, clamped, Base64. */
function generate_private_key(): string
{
    return bytes_to_base64(clamp_private_key(random_bytes(KEY_LENGTH)));
}

/** A fresh pre-shared key: 32 CSPRNG bytes, Base64 — used as-is, never clamped. */
function generate_preshared_key(): string
{
    return bytes_to_base64(random_bytes(KEY_LENGTH));
}

/**
 * Derive the WireGuard public key that pairs with a Base64 private key
 * (Curve25519 scalar multiplication of the base point u = 9).
 */
function private_key_to_public(string $private_key_base64): string
{
    $priv = base64_to_bytes($private_key_base64);
    if (strlen($priv) !== KEY_LENGTH) {
        throw new InvalidArgumentException(
            'Invalid private key: expected ' . KEY_LENGTH . " bytes, got " . strlen($priv)
        );
    }
    $base_point = "\x09" . str_repeat("\0", KEY_LENGTH - 1); // u = 9, little-endian
    return bytes_to_base64(curve25519($priv, $base_point));
}

/** A fresh WireGuard key pair (private + matching public key, both Base64). */
function generate_wireguard_keys(): array
{
    $privateKey = generate_private_key();
    return ['private_key' => $privateKey, 'public_key' => private_key_to_public($privateKey)];
}

/**
 * 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).
 */
function format_config(array $keys, ?string $psk = null): string
{
    $lines = [
        '[Interface]',
        '# Your side — keep PrivateKey secret, share PublicKey with the peer',
        "PrivateKey = {$keys['private_key']}",
        "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 !== null && $psk !== '') {
        $lines[] = '# Optional pre-shared key — the same value must be set on BOTH sides';
        $lines[] = "PresharedKey = {$psk}";
    }
    $lines[] = '# Route everything through the tunnel (or scope it, e.g. 10.0.0.0/24)';
    $lines[] = 'AllowedIPs = 0.0.0.0/0, ::/0';
    $lines[] = "# The peer's public address and port";
    $lines[] = 'Endpoint = vpn.example.com:51820';
    $lines[] = 'PersistentKeepalive = 25';
    return implode("\n", $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 →