OpenBSD Wireguard Keygen Script


WireGuard has been officially included in OpenBSD as a native, in-kernel implementation since OpenBSD 6.8 released in October 2020.

It is quite simple to create a private WireGuard key using the “openssl” command. However, the process of key derivation from a known private key isn’t as simple.

This is a simple little script that I wrote to solve the problem of generating a WireGuard keypair using only the tools from a base install without the need for any additional software:

#!/bin/sh

umask 077

### Generate Private Key Funtion ###
private_key_gen() {
    /usr/bin/openssl rand -base64 32
}

### Derive Public Key Using OpenBSD Kernel Function ###
public_key_gen() {
    _privkey="$1"

    /sbin/ifconfig wg9 create wgkey "$_privkey" >/dev/null 2>&1
    _pubkey=$(/sbin/ifconfig wg9 | /usr/bin/awk '/wgpubkey/ { print $2 }' 2>/dev/null 2>&1)
    /sbin/ifconfig wg9 destroy >/dev/null 2>&1

    printf '%s\n' "$_pubkey"
}

### Main ###

### Generate Private Key ###
PRIVATE_KEY=$(private_key_gen)

### Derive Public Key Using OpenBSD Kernel ###
PUBLIC_KEY=$(public_key_gen "$PRIVATE_KEY")

printf 'Private Key:\n%s\n\n' "$PRIVATE_KEY"
printf 'Public Key:\n%s\n' "$PUBLIC_KEY"