How to generate WireGuard key (private & public) in Python without dependencies

The following code allows you to generate a WireGuard private & public key without having to install any Python library.

import subprocess

def generate_wireguard_keys():
    """
    Generate a WireGuard private & public key
    Requires that the 'wg' command is available on PATH
    Returns (private_key, public_key), both strings
    """
    privkey = subprocess.check_output("wg genkey", shell=True).decode("utf-8").strip()
    pubkey = subprocess.check_output(f"echo '{privkey}' | wg pubkey", shell=True).decode("utf-8").strip()
    return (privkey, pubkey)

Usage example:

print(generate_wireguard_key())

Output:

('KIm+ZlY86I+cInG4FWZpKmhADUnxrqhdtQ5UzaFbuVs=', 'ctX9oUw+CkRe7GfSmUHAB9JjLfQWALOs0gXU9Ikhg1g=')