PGP Encrypt & Decrypt — Python source
Encrypt or decrypt messages with PGP public/private keys. Powered by OpenPGP.js, runs entirely in your browser.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""pgp-encrypt — read OpenPGP key metadata, encrypt (optionally signing), decrypt.
Language: Python 3 (standard library only — subprocess/tempfile drive the
`gpg` binary, the same engine the C port reaches through GPGME and the native
counterpart to the TS reference's openpgp.js).
CosmoDev polyglot showcase port of the `pgp-encrypt` tool, ported from
src/lib/pgp-encrypt.ts (the canonical TypeScript implementation).
gpg always gets an argument ARRAY (subprocess.run, shell=False) — no key,
message or passphrase is ever parsed by a shell — and armored keys are
imported into a fresh 0700 GNUPGHOME deleted on the way out.
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
from datetime import datetime, timezone
# gpg numeric public-key algorithm ids -> openpgp.js-style names.
ALGO_NAMES = {1: "rsa", 2: "rsa", 3: "rsa", 16: "elgamal", 17: "dsa",
18: "ecdh", 19: "ecdsa", 22: "ed25519", 27: "x25519"}
@dataclass
class PGPKeyInfo: # One armored PGP key's metadata (PGPKeyInfo in the TS reference).
userID: str
fingerprint: str
algorithm: str
creationDate: str # ISO yyyy-MM-dd.
expiry: str | None # ISO yyyy-MM-dd, None when the key never expires.
isPrivate: bool
def _gpg(home: str, args: list[str], stdin: str = "") -> str:
"""Run gpg inside ``home``; argv array, never a shell."""
proc = subprocess.run(["gpg", "--homedir", home, "--batch", "--yes", *args],
input=stdin, capture_output=True, text=True)
if proc.returncode != 0:
raise RuntimeError((proc.stderr or f"gpg exited {proc.returncode}").strip())
return proc.stdout
def _import(home: str, armored: str) -> str:
"""Import one armored key, returning its fingerprint (--import-options
import-show lists exactly what was imported, so it is always that key)."""
shown = _gpg(home, ["--import-options", "import-show", "--with-colons", "--import"], armored)
return _primary(shown)["fingerprint"]
def _primary(colons: str) -> dict:
"""Parse the first primary key from ``gpg --with-colons`` output. Fields:
pub[3]=algo [5]=creation [6]=expiry (epoch secs); fpr[9]=fpr; uid[9]=user id."""
pub = fpr = uid = None
for line in colons.splitlines():
f = line.split(":")
if f[0] == "pub" and pub is None:
pub = f
elif f[0] == "fpr" and fpr is None:
fpr = f[9]
elif f[0] == "uid" and uid is None:
# gpg escapes non-printable userid bytes as \xNN; decode them back.
uid = re.sub(r"\\x([0-9a-fA-F]{2})", lambda m: chr(int(m[1], 16)), f[9])
if pub is None or fpr is None:
raise RuntimeError("unrecognized key format")
iso = lambda sec: datetime.fromtimestamp( # noqa: E731 — UTC date, as toISOString().
int(sec), tz=timezone.utc).date().isoformat()
return {"userID": uid or "unknown", "fingerprint": fpr.upper(),
"algorithm": ALGO_NAMES.get(int(pub[3]), f"algo-{pub[3]}"),
"creationDate": iso(pub[5]), "expiry": iso(pub[6]) if pub[6] else None}
@contextmanager
def _temp_home():
"""A fresh 0700 GNUPGHOME under a temp dir, deleted on the way out."""
home = tempfile.mkdtemp(prefix="gnupg-")
os.chmod(home, 0o700)
try:
yield home
finally:
shutil.rmtree(home, ignore_errors=True)
def read_key_info(armored_key: str) -> PGPKeyInfo:
"""Read a PGP key (public or private); ValueError on empty/invalid input."""
if not armored_key:
raise ValueError("Key input is empty or invalid.")
trimmed = armored_key.strip()
is_private = ("-----BEGIN PGP PRIVATE KEY BLOCK-----" in trimmed
or "-----BEGIN PGP SECRET KEY BLOCK-----" in trimmed)
with _temp_home() as home:
try:
_gpg(home, ["--import"], trimmed)
info = _primary(_gpg(home, ["--with-colons", "--list-keys"]))
except RuntimeError as exc:
raise ValueError(f"Invalid PGP key: {exc}") from exc
return PGPKeyInfo(isPrivate=is_private, **info)
def pgp_encrypt(message: str, public_key_armored: str,
signing_private_key_armored: str | None = None,
passphrase: str | None = None) -> str:
"""Encrypt for a recipient's public key; optionally sign with the sender's."""
if not message:
raise ValueError("Message must not be empty.")
if not public_key_armored:
raise ValueError("Recipient public key must not be empty.")
with _temp_home() as home:
args = ["--armor", "--recipient", _import(home, public_key_armored.strip()), "--encrypt"]
if signing_private_key_armored:
args += ["--sign", "--local-user", _import(home, signing_private_key_armored.strip()),
"--pinentry-mode", "loopback"]
if passphrase:
args += ["--passphrase", passphrase]
return _gpg(home, args, message)
def pgp_decrypt(armored_message: str, private_key_armored: str,
passphrase: str | None = None) -> str:
"""Decrypt an armored message with the recipient's private key."""
if not armored_message:
raise ValueError("Armored message must not be empty.")
if not private_key_armored:
raise ValueError("Private key must not be empty.")
with _temp_home() as home:
_import(home, private_key_armored.strip())
args = ["--pinentry-mode", "loopback", "--decrypt"]
if passphrase:
args += ["--passphrase", passphrase]
return _gpg(home, args, armored_message.strip())
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 →