Skip to content

PGP Key Generator — Python source

Generate PGP key pairs (ECC or RSA) in your browser. Download your public and private keys. Powered by OpenPGP.js.

This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""pgp-keygen — ASCII-armored OpenPGP key pair generation (ECC Curve25519,
RSA-2048, RSA-4096) with v4 fingerprint and revocation certificate.

Language: Python 3 (standard library only — subprocess/tempfile drive the
`gpg` binary, the engine behind the sibling C/Ruby ports and the native
counterpart to the TS reference's openpgp.js).
CosmoDev polyglot showcase port of the `pgp-keygen` tool, ported from
src/lib/pgp-keygen.ts (the canonical TypeScript implementation).

The TS reference wraps openpgp.js `generateKey`; the Python standard library
ships no asymmetric crypto, so like the sibling ports this one delegates to
GnuPG. Every key is generated in a fresh 0700 GNUPGHOME deleted on the way
out, and gpg always gets an argument ARRAY (subprocess.run, shell=False) so
no identity or passphrase is ever parsed by a shell.

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import os
import re
import shutil
import subprocess
import tempfile
from contextlib import contextmanager
from dataclasses import dataclass

# Mirrors EMAIL_RE in the TS reference: one @, non-empty local + domain with a dot.
_EMAIL_RE = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")

# Algorithm choices, mirroring PGPKeyGenAlgorithm in the TS reference. gpg's
# 'ed25519' = Ed25519 primary + Curve25519 encryption subkey, the TS 'ecc' family.
_ALGORITHMS = {"ecc": "ed25519", "rsa2048": "rsa2048", "rsa4096": "rsa4096"}


@dataclass
class PGPKeyPair:  # PGPKeyPair in the TS reference.
    publicKey: str  # ASCII-armored public key (BEGIN PGP PUBLIC KEY BLOCK).
    privateKey: str  # ASCII-armored private key (BEGIN PGP PRIVATE KEY BLOCK).
    fingerprint: str  # v4 fingerprint, 40 lowercase hex chars, no spaces.
    revocationCertificate: str  # ASCII-armored revocation certificate.


def validate_key_gen_identity(name: str, email: str) -> None:
    """Validate the identity that goes into the key's user ID; ValueError on bad input."""
    if not name.strip():
        raise ValueError("Name is required.")
    if not email.strip():
        raise ValueError("Email is required.")
    if not _EMAIL_RE.match(email.strip()):
        raise ValueError("Invalid email address.")


def _gpg(home: str, args: list[str], passphrase: str | None = None) -> str:
    """Run gpg inside ``home``; argv array, never a shell. The passphrase (an
    empty line for the unprotected case) is fed on stdin via --passphrase-fd 0
    with loopback pinentry — never in the process table, never a tty prompt."""
    proc = subprocess.run(
        ["gpg", "--homedir", home, "--batch", "--no-tty", "--yes",
         "--pinentry-mode", "loopback", "--passphrase-fd", "0", *args],
        input=f"{passphrase or ''}\n", capture_output=True, text=True)
    if proc.returncode != 0:
        raise RuntimeError((proc.stderr or f"gpg exited {proc.returncode}").strip())
    return proc.stdout


@contextmanager
def _ephemeral_home():
    """A fresh 0700 GNUPGHOME under a temp dir, deleted on the way out."""
    home = tempfile.mkdtemp(prefix="cosmodev-pgp-")
    os.chmod(home, 0o700)  # gpg refuses to run against a world-readable home
    try:
        yield home
    finally:
        shutil.rmtree(home, ignore_errors=True)


def _read_fingerprint(home: str) -> str:
    """The primary key's fingerprint: field 10 of the first `fpr` colon record."""
    for line in _gpg(home, ["--list-keys", "--with-colons"]).splitlines():
        if line.startswith("fpr:"):
            return line.split(":")[9].lower()  # TS returns lowercase hex, no spaces
    raise RuntimeError("gpg generated no key (no fingerprint record).")


def generate_pgp_key_pair(name: str, email: str, algorithm: str = "ecc",
                          passphrase: str | None = None) -> PGPKeyPair:
    """Generate an ASCII-armored PGP key pair (ECC/Curve25519 fast, RSA-4096
    slow), returning the TS reference's exact output shape: publicKey,
    privateKey, fingerprint (40 lowercase hex chars) and revocationCertificate.
    Only a real passphrase encrypts the private key, as in the TS reference.

    Raises: ValueError on an invalid identity or unsupported algorithm;
    RuntimeError if gpg fails.
    """
    validate_key_gen_identity(name, email)
    gpg_algorithm = _ALGORITHMS.get(algorithm)
    if gpg_algorithm is None:
        raise ValueError(f"Unsupported algorithm: {algorithm}")
    # An empty-string passphrase would still encrypt the key; only a real
    # passphrase should (same reasoning as the `pass` guard in the TS reference).
    secret = passphrase or None

    with _ephemeral_home() as home:
        # EXPIRE 0 = never expires, matching openpgp.js's default.
        _gpg(home, ["--quick-generate-key", f"{name.strip()} <{email.strip()}>",
                    gpg_algorithm, "default", "0"], passphrase=secret)
        fingerprint = _read_fingerprint(home)
        # gpg writes an armored revocation certificate per key at generation
        # time, under openpgp-revocs.d/<FINGERPRINT>.rev.
        rev_path = os.path.join(home, "openpgp-revocs.d", f"{fingerprint.upper()}.rev")
        return PGPKeyPair(
            publicKey=_gpg(home, ["--armor", "--export", fingerprint]),
            privateKey=_gpg(home, ["--armor", "--export-secret-keys", fingerprint],
                            passphrase=secret),
            fingerprint=fingerprint,
            revocationCertificate=open(rev_path).read() if os.path.exists(rev_path) else "",
        )

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 →