Skip to content

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

// Package wireguardkeygen ports src/lib/wireguard-keygen.ts (dual source: the
// web lib is TypeScript, the CLI lib is Go — kept in lock-step). Pure logic,
// never panics: invalid input returns an error. The table-driven tests in
// wireguard_keygen_test.go share vectors with src/lib/wireguard-keygen.test.ts
// so the two implementations are held to the same contract.
//
// WireGuard uses Curve25519 (RFC 7748 X25519) for its key exchange:
//   - a private key is 32 random bytes, clamped per the Curve25519 rules
//     (key[0] &= 248; key[31] &= 127; key[31] |= 64)
//   - the public key is that scalar multiplied by the curve's base point 9,
//     computed with a pure big.Int Montgomery ladder over GF(2^255 - 19)
//   - an optional pre-shared key is 32 random bytes, used as-is (no clamping)
//
// Every key is serialized as standard Base64 with padding — 44 characters for
// 32 bytes — which is exactly the format WireGuard config files expect.
// Randomness comes from crypto/rand.
package wireguardkeygen

import (
	"crypto/rand"
	"encoding/base64"
	"errors"
	"fmt"
	"math/big"
	"strings"
)

// KeyLength is the length of every WireGuard key, in bytes. Mirrors KEY_LENGTH.
const KeyLength = 32

// WireGuardKeys is a fresh key pair, both keys standard-padded Base64.
// Mirrors the WireGuardKeys interface.
type WireGuardKeys struct {
	PrivateKey string
	PublicKey  string
}

// Curve25519 domain parameters: y^2 = x^3 + 486662x^2 + x over GF(2^255 - 19).
var (
	p    = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 255), big.NewInt(19))
	a24  = big.NewInt(121665) // (486662 - 2) / 4
	mask = new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 255), big.NewInt(1))
)

// basePoint is u = 9, little-endian (the X25519 generator).
var basePoint = func() []byte {
	b := make([]byte, KeyLength)
	b[0] = 9
	return b
}()

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

// b64Index maps every standard-alphabet character to its 6-bit value.
// -1 marks an invalid character (mirrors B64_ALPHABET.indexOf(ch) === -1).
var b64Index = func() [256]int8 {
	var idx [256]int8
	for i := range idx {
		idx[i] = -1
	}
	const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
	for i := range len(alphabet) {
		idx[alphabet[i]] = int8(i)
	}
	return idx
}()

// BytesToBase64 encodes bytes as standard Base64 with '=' padding
// (32 bytes → 44 chars). Mirrors bytesToBase64().
func BytesToBase64(b []byte) string {
	return base64.StdEncoding.EncodeToString(b)
}

// Base64ToBytes decodes standard Base64 (with padding), mirroring the lenient
// TS decoder: surrounding whitespace is trimmed, an unpadded string whose
// length is still a multiple of 4 is accepted, and any other length or any
// non-alphabet character is an error. Mirrors base64ToBytes().
func Base64ToBytes(b64 string) ([]byte, error) {
	s := strings.TrimSpace(b64)
	if len(s) == 0 || len(s)%4 != 0 {
		return nil, errors.New("Invalid Base64: length must be a non-zero multiple of 4")
	}
	pad := 0
	if strings.HasSuffix(s, "==") {
		pad = 2
	} else if strings.HasSuffix(s, "=") {
		pad = 1
	}
	data := s[:len(s)-pad]
	out := make([]byte, len(s)/4*3-pad)
	var buffer uint32
	bits := 0
	o := 0
	for i := 0; i < len(data); i++ {
		ch := data[i]
		v := b64Index[ch]
		if v < 0 {
			return nil, fmt.Errorf("Invalid Base64 character: %q", string(ch))
		}
		buffer = buffer<<6 | uint32(v)
		bits += 6
		if bits >= 8 {
			bits -= 8
			out[o] = byte(buffer >> bits & 0xff)
			o++
		}
	}
	return out, nil
}

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

// mod reduces a into the canonical range [0, P). big.Int.Mod is Euclidean, so
// the result is non-negative for negative inputs — same as the TS mod().
func mod(a *big.Int) *big.Int { return new(big.Int).Mod(a, p) }

// powMod computes base^exponent mod P via square-and-multiply (used for field
// inversion). Mirrors powMod().
func powMod(base, exponent *big.Int) *big.Int {
	result := big.NewInt(1)
	b := mod(base)
	e := new(big.Int).Set(exponent)
	for e.Sign() > 0 {
		if e.Bit(0) == 1 {
			result = mod(new(big.Int).Mul(result, b))
		}
		b = mod(new(big.Int).Mul(b, b))
		e.Rsh(e, 1)
	}
	return result
}

// ClampPrivateKey clamps 32 bytes into a valid Curve25519 scalar (RFC 7748 §5)
// and returns the clamped copy — the input is left untouched. Mirrors
// clampPrivateKey().
func ClampPrivateKey(key []byte) ([]byte, error) {
	if len(key) != KeyLength {
		return nil, fmt.Errorf("Private key must be %d bytes, got %d", KeyLength, len(key))
	}
	out := make([]byte, KeyLength)
	copy(out, 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 out, nil
}

// decodeLittleEndian interprets bytes as a little-endian unsigned integer.
func decodeLittleEndian(b []byte) *big.Int {
	rev := make([]byte, len(b))
	for i, v := range b {
		rev[len(b)-1-i] = v
	}
	return new(big.Int).SetBytes(rev)
}

// encodeLittleEndian serializes n into exactly KeyLength little-endian bytes.
func encodeLittleEndian(n *big.Int) []byte {
	be := make([]byte, KeyLength)
	n.FillBytes(be)
	for i, j := 0, KeyLength-1; i < j; i, j = i+1, j-1 {
		be[i], be[j] = be[j], be[i]
	}
	return be
}

// Curve25519 computes the X25519 scalar multiplication scalar · u — the
// RFC 7748 Montgomery ladder in plain big.Int 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). Mirrors curve25519().
func Curve25519(scalar, u []byte) ([]byte, error) {
	if len(scalar) != KeyLength {
		return nil, fmt.Errorf("Scalar must be %d bytes, got %d", KeyLength, len(scalar))
	}
	if len(u) != KeyLength {
		return nil, fmt.Errorf("u-coordinate must be %d bytes, got %d", KeyLength, len(u))
	}
	clamped, err := ClampPrivateKey(scalar)
	if err != nil {
		return nil, err
	}
	k := decodeLittleEndian(clamped)
	// Mask the most significant bit of the u-coordinate per RFC 7748 §5.
	x1 := new(big.Int).And(decodeLittleEndian(u), mask)

	add := func(x, y *big.Int) *big.Int { return new(big.Int).Add(x, y) }
	sub := func(x, y *big.Int) *big.Int { return new(big.Int).Sub(x, y) }
	mul := func(x, y *big.Int) *big.Int { return new(big.Int).Mul(x, y) }

	x2 := big.NewInt(1)
	z2 := big.NewInt(0)
	x3 := new(big.Int).Set(x1)
	z3 := big.NewInt(1)
	swap := uint(0)
	for t := 254; t >= 0; t-- {
		bit := k.Bit(t)
		swap ^= bit
		if swap == 1 {
			x2, x3 = x3, x2
			z2, z3 = z3, z2
		}
		swap = bit

		a := mod(add(x2, z2))
		aa := mod(mul(a, a))
		b := mod(sub(x2, z2))
		bb := mod(mul(b, b))
		e := mod(sub(aa, bb))
		c := mod(add(x3, z3))
		d := mod(sub(x3, z3))
		da := mod(mul(d, a))
		cb := mod(mul(c, b))
		sum := mod(add(da, cb))
		diff := mod(sub(da, cb))
		x3 = mod(mul(sum, sum))
		z3 = mod(mul(x1, mod(mul(diff, diff))))
		x2 = mod(mul(aa, bb))
		z2 = mod(mul(e, mod(add(aa, 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.
	inverse := powMod(z2, new(big.Int).Sub(p, big.NewInt(2)))
	return encodeLittleEndian(mod(mul(x2, inverse))), nil
}

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

// randomBytes reads length CSPRNG bytes (crypto/rand — the Go counterpart of
// crypto.getRandomValues).
func randomBytes(length int) ([]byte, error) {
	b := make([]byte, length)
	if _, err := rand.Read(b); err != nil {
		return nil, fmt.Errorf("reading random bytes: %w", err)
	}
	return b, nil
}

// GeneratePrivateKey returns a fresh private key: 32 CSPRNG bytes, clamped,
// Base64. Mirrors generatePrivateKey().
func GeneratePrivateKey() (string, error) {
	raw, err := randomBytes(KeyLength)
	if err != nil {
		return "", err
	}
	clamped, err := ClampPrivateKey(raw)
	if err != nil {
		return "", err
	}
	return BytesToBase64(clamped), nil
}

// GeneratePresharedKey returns a fresh pre-shared key: 32 CSPRNG bytes,
// Base64 — used as-is, never clamped. Mirrors generatePresharedKey().
func GeneratePresharedKey() (string, error) {
	raw, err := randomBytes(KeyLength)
	if err != nil {
		return "", err
	}
	return BytesToBase64(raw), nil
}

// PrivateKeyToPublic derives the WireGuard public key that pairs with a Base64
// private key (Curve25519 scalar multiplication of the base point). The TS lib
// is async only so a WebCrypto backend could drop in; the math is synchronous,
// so the Go twin is too. Mirrors privateKeyToPublic().
func PrivateKeyToPublic(privateKeyBase64 string) (string, error) {
	priv, err := Base64ToBytes(privateKeyBase64)
	if err != nil {
		return "", err
	}
	if len(priv) != KeyLength {
		return "", fmt.Errorf("Invalid private key: expected %d bytes, got %d", KeyLength, len(priv))
	}
	pub, err := Curve25519(priv, basePoint)
	if err != nil {
		return "", err
	}
	return BytesToBase64(pub), nil
}

// GenerateWireGuardKeys returns a fresh WireGuard key pair (private + matching
// public key, both Base64). Mirrors generateWireGuardKeys().
func GenerateWireGuardKeys() (WireGuardKeys, error) {
	privateKey, err := GeneratePrivateKey()
	if err != nil {
		return WireGuardKeys{}, err
	}
	publicKey, err := PrivateKeyToPublic(privateKey)
	if err != nil {
		return WireGuardKeys{}, err
	}
	return WireGuardKeys{PrivateKey: privateKey, PublicKey: publicKey}, nil
}

// ---------------------------------------------------------------------------
// Config template
// ---------------------------------------------------------------------------

// FormatConfig renders 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 non-empty ("" mirrors an omitted psk parameter — either way the
// line is skipped) and it must be present on BOTH sides of the tunnel.
// Mirrors formatConfig().
func FormatConfig(keys WireGuardKeys, psk string) string {
	lines := []string{
		"[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 != "" {
		lines = append(lines,
			"# Optional pre-shared key — the same value must be set on BOTH sides",
			"PresharedKey = "+psk,
		)
	}
	lines = append(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 strings.Join(lines, "\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 →