WireGuard Key Generator — Rust 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 Rust implementation — the same logic the interactive tool runs, in a shareable, citable form.
//! wireguard-keygen — WireGuard key generation (Curve25519 / RFC 7748 X25519).
//!
//! Language: Rust (std only — no external crates).
//! CosmoDev polyglot showcase port of the `wireguard-keygen` tool, ported from
//! src/lib/wireguard-keygen.ts (the canonical TypeScript implementation).
//!
//! Rust's standard library has neither bignums nor a CSPRNG, so this port
//! substitutes both: the GF(2^255 - 19) field arithmetic is hand-rolled over
//! `[u64; 4]` limbs (the stand-in for the reference's BigInts), and key
//! randomness is read from `/dev/urandom` via `std::fs` — the same spirit in
//! which the C/C++ ports reach for OpenSSL's RAND. On non-Unix platforms,
//! swap `random_bytes` for the `getrandom` crate's fill. Every key serializes
//! as standard padded Base64 (44 chars for 32 bytes), what WireGuard expects.
//!
//! display source — part of CosmoDev's polyglot tool pages.
/// Length of every WireGuard key, in bytes.
pub const KEY_LENGTH: usize = 32;
/// The field prime p = 2^255 - 19 (little-endian u64 limbs: the low limb ends
/// in ...ffed and the top limb holds the single high bit 0x7fff…).
type Fe = [u64; 4];
const P: Fe = [0xffff_ffff_ffff_ffed, u64::MAX, u64::MAX, 0x7fff_ffff_ffff_ffff];
/// p - 2 — the exponent for Fermat inversion: z^(p-2) ≡ z^(-1) (mod p).
const P_MINUS_2: Fe = [
0xffff_ffff_ffff_ffeb,
u64::MAX,
u64::MAX,
0x7fff_ffff_ffff_ffff,
];
/// The Curve25519 base point u = 9, little-endian.
const BASE_POINT: [u8; KEY_LENGTH] = {
let mut b = [0u8; KEY_LENGTH];
b[0] = 9;
b
};
/// (486662 - 2) / 4 — the ladder's curve constant.
const A24: Fe = [121_665, 0, 0, 0];
// ---------------------------------------------------------------------------
// Field arithmetic over GF(2^255 - 19), on little-endian [u64; 4] limbs
// ---------------------------------------------------------------------------
/// Return x - p when x >= p, else x unchanged.
fn fe_sub_p(x: Fe) -> Fe {
let mut diff = [0u64; 4];
let mut borrow = 0u64;
for i in 0..4 {
let (d, b1) = x[i].overflowing_sub(P[i]);
let (d, b2) = d.overflowing_sub(borrow);
diff[i] = d;
borrow = (b1 as u64) | (b2 as u64);
}
if borrow == 0 { diff } else { x }
}
/// Reduce into the canonical range [0, p). Every caller guarantees x < 3p,
/// so two conditional subtractions always suffice.
fn fe_canonical(x: Fe) -> Fe {
fe_sub_p(fe_sub_p(x))
}
/// (a + b) mod p. Inputs are canonical, so the 256-bit sum never overflows.
fn fe_add(a: Fe, b: Fe) -> Fe {
let mut r = [0u64; 4];
let mut carry = 0u128;
for i in 0..4 {
let t = a[i] as u128 + b[i] as u128 + carry;
r[i] = t as u64;
carry = t >> 64;
}
fe_canonical(r)
}
/// (a - b) mod p, computed as a + p - b — no underflow since b < p ≤ a + p.
fn fe_sub(a: Fe, b: Fe) -> Fe {
let mut r = [0u64; 4];
let mut carry = 0u128;
for i in 0..4 {
let t = a[i] as u128 + P[i] as u128 + carry;
r[i] = t as u64;
carry = t >> 64;
}
let mut borrow = 0u64;
for i in 0..4 {
let (d, b1) = r[i].overflowing_sub(b[i]);
let (d, b2) = d.overflowing_sub(borrow);
r[i] = d;
borrow = (b1 as u64) | (b2 as u64);
}
fe_canonical(r)
}
/// (a * b) mod p — schoolbook multiplication into 512 bits, then reduction.
fn fe_mul(a: Fe, b: Fe) -> Fe {
let mut w = [0u64; 8];
for i in 0..4 {
let mut carry = 0u128;
for j in 0..4 {
let t = a[i] as u128 * b[j] as u128 + w[i + j] as u128 + carry;
w[i + j] = t as u64;
carry = t >> 64;
}
w[i + 4] = carry as u64;
}
fe_reduce_wide(w)
}
/// Reduce a 512-bit little-endian value modulo p = 2^255 - 19, via the fold
/// 2^256 ≡ 38 (mod p): w = lo + 2^256·hi ≡ lo + 38·hi (folded twice).
fn fe_reduce_wide(w: [u64; 8]) -> Fe {
// acc = lo + 38·hi as a 5-limb (320-bit) accumulator; 38·hi < 2^262.
let mut acc = [0u64; 5];
acc[..4].copy_from_slice(&w[..4]);
let mut carry: u128 = 0;
for i in 0..4 {
let t = w[4 + i] as u128 * 38 + carry + acc[i] as u128;
acc[i] = t as u64;
carry = t >> 64;
}
acc[4] = carry as u64;
// Fold the 5th limb back in: the correction term is tiny (acc[4] < 2^7).
// Adding c to the low limb can overflow 2^256 only once or twice, and each
// overflow folds back as a fresh ×38 correction — so the loop exits fast.
let mut r = [acc[0], acc[1], acc[2], acc[3]];
let mut c: u128 = acc[4] as u128 * 38;
while c > 0 {
let mut carry = c;
for r_i in r.iter_mut() {
let t = *r_i as u128 + carry;
*r_i = t as u64;
carry = t >> 64;
}
c = carry * 38; // carry ∈ {0,1}: overflow above 2^256, ≡ 38 (mod p)
}
fe_canonical(r) // r < 2^256 < 3p, so two conditional subtractions suffice
}
/// `base^e mod p` via square-and-multiply over the exponent's bits.
fn fe_pow(mut base: Fe, mut e: Fe) -> Fe {
let mut result: Fe = [1, 0, 0, 0];
while e != [0, 0, 0, 0] {
if e[0] & 1 == 1 {
result = fe_mul(result, base);
}
base = fe_mul(base, base);
let mut carry = 0u64; // e >>= 1
for limb in e.iter_mut().rev() {
let top = *limb & 1;
*limb = (*limb >> 1) | (carry << 63);
carry = top;
}
}
result
}
fn fe_from_le(bytes: &[u8]) -> Fe {
let mut fe = [0u64; 4];
for (i, chunk) in bytes.chunks(8).enumerate() {
let mut limb = 0u64;
for (j, &byte) in chunk.iter().enumerate() {
limb |= (byte as u64) << (8 * j);
}
fe[i] = limb;
}
fe
}
fn fe_to_le(fe: Fe) -> Vec<u8> {
fe.iter().flat_map(|limb| limb.to_le_bytes()).collect()
}
// ---------------------------------------------------------------------------
// Base64 codec (standard alphabet, always padded — the WireGuard format)
// ---------------------------------------------------------------------------
const B64_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// Encode bytes as standard Base64 with `=` padding (32 bytes → 44 chars).
pub fn bytes_to_base64(bytes: &[u8]) -> String {
let mut out = String::new();
for chunk in bytes.chunks(3) {
let b1 = chunk.get(1).copied().unwrap_or(0);
let b2 = chunk.get(2).copied().unwrap_or(0);
let n = ((chunk[0] as u32) << 16) | ((b1 as u32) << 8) | b2 as u32;
out.push(B64_ALPHABET[(n >> 18) as usize & 0x3f] as char);
out.push(B64_ALPHABET[(n >> 12) as usize & 0x3f] as char);
out.push(if chunk.len() > 1 { B64_ALPHABET[(n >> 6) as usize & 0x3f] as char } else { '=' });
out.push(if chunk.len() > 2 { B64_ALPHABET[n as usize & 0x3f] as char } else { '=' });
}
out
}
/// Decode standard Base64 (with padding). Errors on invalid input.
pub fn base64_to_bytes(b64: &str) -> Result<Vec<u8>, String> {
let s = b64.trim();
if s.is_empty() || s.len() % 4 != 0 {
return Err("Invalid Base64: length must be a non-zero multiple of 4".into());
}
let pad = if s.ends_with("==") {
2
} else if s.ends_with('=') {
1
} else {
0
};
let mut out = Vec::with_capacity(s.len() / 4 * 3 - pad);
let mut buffer = 0u32;
let mut bits = 0u32;
for ch in s[..s.len() - pad].chars() {
let v = B64_ALPHABET
.iter()
.position(|&c| c as char == ch)
.ok_or_else(|| format!("Invalid Base64 character: {ch:?}"))?
as u32;
buffer = (buffer << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push(((buffer >> bits) & 0xff) as u8);
}
}
Ok(out)
}
// ---------------------------------------------------------------------------
// Curve25519 scalar multiplication (RFC 7748 Montgomery ladder) + keygen
// ---------------------------------------------------------------------------
/// Clamp 32 bytes into a valid Curve25519 scalar (RFC 7748 §5). Returns a copy.
pub fn clamp_private_key(key: &[u8]) -> Result<Vec<u8>, String> {
if key.len() != KEY_LENGTH {
return Err(format!("Private key must be {KEY_LENGTH} bytes, got {}", key.len()));
}
let mut out = key.to_vec();
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
Ok(out)
}
/// X25519 scalar multiplication `scalar · u` — the RFC 7748 Montgomery ladder
/// in plain limb arithmetic. The scalar is clamped internally (an unclamped
/// input yields the same result as its clamped form, like every X25519 impl).
pub fn curve25519(scalar: &[u8], u: &[u8]) -> Result<Vec<u8>, String> {
if scalar.len() != KEY_LENGTH {
return Err(format!("Scalar must be {KEY_LENGTH} bytes, got {}", scalar.len()));
}
if u.len() != KEY_LENGTH {
return Err(format!("u-coordinate must be {KEY_LENGTH} bytes, got {}", u.len()));
}
let k = fe_from_le(&clamp_private_key(scalar)?);
let mut x1 = fe_from_le(u);
x1[3] &= 0x7fff_ffff_ffff_ffff; // mask the top bit per RFC 7748 §5
let mut x2: Fe = [1, 0, 0, 0];
let mut z2: Fe = [0, 0, 0, 0];
let mut x3 = x1;
let mut z3: Fe = [1, 0, 0, 0];
let mut swap = 0u64;
for t in (0..255).rev() {
let bit = (k[t / 64] >> (t % 64)) & 1;
swap ^= bit;
if swap == 1 {
std::mem::swap(&mut x2, &mut x3);
std::mem::swap(&mut z2, &mut z3);
}
swap = bit;
let a = fe_add(x2, z2);
let aa = fe_mul(a, a);
let b = fe_sub(x2, z2);
let bb = fe_mul(b, b);
let e = fe_sub(aa, bb);
let c = fe_add(x3, z3);
let d = fe_sub(x3, z3);
let da = fe_mul(d, a);
let cb = fe_mul(c, b);
let sum = fe_add(da, cb);
let diff = fe_sub(da, cb);
x3 = fe_mul(sum, sum);
z3 = fe_mul(x1, fe_mul(diff, diff));
x2 = fe_mul(aa, bb);
z2 = fe_mul(e, fe_add(aa, fe_mul(A24, e)));
}
// No final cswap: clamping clears bit 0, so swap is provably 0 here.
// x2 / z2 via z2^(P-2) (Fermat): the affine u-coordinate result.
Ok(fe_to_le(fe_mul(x2, fe_pow(z2, P_MINUS_2))))
}
/// Fill `buf` with cryptographically random bytes from the OS entropy pool.
/// (std has no CSPRNG — see the header note for the substitution.)
fn random_bytes(len: usize) -> std::io::Result<Vec<u8>> {
use std::io::Read;
let mut buf = vec![0u8; len];
std::fs::File::open("/dev/urandom")?.read_exact(&mut buf)?;
Ok(buf)
}
/// A fresh private key: 32 CSPRNG bytes, clamped, Base64.
pub fn generate_private_key() -> std::io::Result<String> {
let raw = random_bytes(KEY_LENGTH)?;
Ok(bytes_to_base64(&clamp_private_key(&raw).expect("32 bytes")))
}
/// A fresh pre-shared key: 32 CSPRNG bytes, Base64 — used as-is, never clamped.
pub fn generate_preshared_key() -> std::io::Result<String> {
Ok(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).
pub fn private_key_to_public(private_key_base64: &str) -> Result<String, String> {
let priv_bytes = base64_to_bytes(private_key_base64)?;
if priv_bytes.len() != KEY_LENGTH {
return Err(format!(
"Invalid private key: expected {KEY_LENGTH} bytes, got {}",
priv_bytes.len()
));
}
Ok(bytes_to_base64(&curve25519(&priv_bytes, &BASE_POINT)?))
}
/// A fresh WireGuard key pair (private + matching public key, both Base64).
pub fn generate_wireguard_keys() -> std::io::Result<(String, String)> {
let private_key = generate_private_key()?;
let public_key = private_key_to_public(&private_key).expect("valid generated key");
Ok((private_key, public_key))
}
/// Render a `wg-quick` config template around a key pair. The peer's public
/// key, endpoint, and tunnel address stay as placeholders. A `PresharedKey`
/// line is included only when `psk` is `Some` (it must be present on BOTH
/// sides of the tunnel).
pub fn format_config(private_key: &str, public_key: &str, psk: Option<&str>) -> String {
let mut lines = vec![
"[Interface]".to_string(),
"# Your side — keep PrivateKey secret, share PublicKey with the peer".into(),
format!("PrivateKey = {private_key}"),
format!("PublicKey = {public_key}"),
"# Tunnel address assigned by your server (plus optional tunnel DNS)".into(),
"Address = 10.0.0.2/32".into(),
"# DNS = 1.1.1.1".into(),
String::new(),
"[Peer]".into(),
"# The other side's public key".into(),
"PublicKey = <PEER_PUBLIC_KEY>".into(),
];
if let Some(psk) = psk.filter(|p| !p.is_empty()) {
lines.push("# Optional pre-shared key — the same value must be set on BOTH sides".into());
lines.push(format!("PresharedKey = {psk}"));
}
lines.push("# Route everything through the tunnel (or scope it, e.g. 10.0.0.0/24)".into());
lines.push("AllowedIPs = 0.0.0.0/0, ::/0".into());
lines.push("# The peer's public address and port".into());
lines.push("Endpoint = vpn.example.com:51820".into());
lines.push("PersistentKeepalive = 25".into());
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 →