Overview

This module provides functions to generate wireguard private keys, preshared keys and public keys. Exposes functions that mimic wg genkey, wg genpsk and wg pubkey commands that work with strings. As well as underlying functions that work with Uint8Arrays.

import { wgGenKey, wgGenPsk, wgPubKey } from "@hertzg/wg-keys";
import { assertExists, assertNotEquals } from "@std/assert";

const privateKey = wgGenKey(); // returns string
const publicKey = await wgPubKey(privateKey); // returns string
const presharedKey = wgGenPsk(); // returns string

assertExists(privateKey);
assertExists(presharedKey);
assertExists(publicKey);

assertNotEquals(privateKey, publicKey);
assertNotEquals(privateKey, presharedKey);
assertNotEquals(publicKey, presharedKey);

or

import { randomPrivateKeyBytes, publicBytesFromPrivateBytes, randomPresharedKeyBytes } from "@hertzg/wg-keys";
import { assertEquals, assertNotEquals } from "@std/assert";

const privateKey = randomPrivateKeyBytes(); // returns Uint8Array
const publicKey = await publicBytesFromPrivateBytes(privateKey); // returns Uint8Array
const presharedKey = randomPresharedKeyBytes(); // returns Uint8Array

assertEquals(privateKey.length, 32);
assertEquals(publicKey.length, 32);
assertEquals(presharedKey.length, 32);

assertNotEquals(privateKey, publicKey);
assertNotEquals(privateKey, presharedKey);
assertNotEquals(publicKey, presharedKey);

Importing Existing Keys

You can import existing WireGuard keys using importPrivateKey and importPublicKey:

import { importPrivateKey, importPublicKey, wgGenKey, wgPubKey } from "@hertzg/wg-keys";
import { assertEquals } from "@std/assert";

const privateKeyBase64 = wgGenKey();
const publicKeyBase64 = await wgPubKey(privateKeyBase64);

const privateCryptoKey = await importPrivateKey(privateKeyBase64);
const publicCryptoKey = await importPublicKey(publicKeyBase64);

assertEquals(privateCryptoKey.type, "private");
assertEquals(publicCryptoKey.type, "public");

OK, But Why?

ℹ️ Since deno v2.1.4 supports JWK export of x25519 private keys, this module has dropped the dependency on @noble/curves and uses CryptoSubtle directly. If you need to support older versions of Deno, you can use wg-keys@0.1.7 version of this module

See X25519 issue for more info.

References