Skip to content

PGP Key Generator — Rust source

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

This is the Rust 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 a v4 fingerprint and a revocation certificate.
//!
//! Language: Rust (std only — no external crates; std::process::Command drives
//! the `gpg` binary, 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).
//!
//! gpg gets an argv vector, never a shell, and a fresh 0700 GNUPGHOME deleted
//! on drop — the Rust equivalent of the TS island generating keys entirely
//! client-side. Err(String) mirrors the TS port's throws.
//!
//! display source — part of CosmoDev's polyglot tool pages.

use std::{fs, io::Write, os::unix::fs::PermissionsExt, path::PathBuf, process::{Command, Stdio}};

/// Algorithm choices: ECC Curve25519 (default), RSA-2048, or RSA-4096.
pub enum Algorithm { Ecc, Rsa2048, Rsa4096 }

/// The four outputs of one generation run (PGPKeyPair in the TS reference).
pub struct KeyPair {
    pub public_key: String,
    pub private_key: String,
    pub fingerprint: String,
    pub revocation_certificate: String,
}

/// Validate the identity that goes into the key's user ID. Throws on invalid input.
pub fn validate_key_gen_identity(name: &str, email: &str) -> Result<(), String> {
    if name.trim().is_empty() { return Err("Name is required.".into()); }
    if email.trim().is_empty() { return Err("Email is required.".into()); }
    // Mirrors EMAIL_RE: one @, non-empty local part, dotted domain, no whitespace.
    let email = email.trim();
    let ok = matches!(email.split_once('@'), Some((local, domain))
        if !local.is_empty() && !domain.contains('@') && !email.chars().any(char::is_whitespace)
            && matches!(domain.split_once('.'), Some((a, b)) if !a.is_empty() && !b.is_empty()));
    if !ok { return Err("Invalid email address.".into()); }
    Ok(())
}

/// The line-oriented batch parameter file: control characters would inject
/// directives, angle brackets would corrupt the "Name <Email>" grammar.
fn assert_safe_field(value: &str) -> Result<(), String> {
    if value.bytes().any(|b| b < 0x20 || b == 0x7f || b == b'<' || b == b'>') {
        Err("Name, email or passphrase contains unsafe characters.".into())
    } else { Ok(()) }
}

/// A fresh 0700 GNUPGHOME under a temp dir, deleted on drop, so keys never
/// land in the user's real keyring.
struct TempHome(PathBuf);
impl Drop for TempHome { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.0); } }

impl TempHome {
    fn new() -> Result<Self, String> {
        let dir = std::env::temp_dir().join(format!("gnupg-keygen-{}", std::process::id()));
        fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
        fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).map_err(|e| e.to_string())?;
        Ok(Self(dir))
    }
    /// Run gpg: argv vector, never a shell; `stdin` in, stdout out, stderr as Err.
    fn gpg(&self, args: &[&str], stdin: &str, passphrase: Option<&str>) -> Result<String, String> {
        let mut cmd = Command::new("gpg");
        cmd.arg("--homedir").arg(&self.0).args(["--batch", "--yes", "--no-tty"]);
        if let Some(p) = passphrase { cmd.args(["--pinentry-mode", "loopback", "--passphrase"]).arg(p); }
        let mut child = cmd.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped())
            .spawn().map_err(|e| e.to_string())?;
        child.stdin.take().unwrap().write_all(stdin.as_bytes()).map_err(|e| e.to_string())?;
        let out = child.wait_with_output().map_err(|e| e.to_string())?;
        if !out.status.success() { return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); }
        String::from_utf8(out.stdout).map_err(|_| "gpg emitted non-UTF-8 output".into())
    }
}

/// The `--gen-key` batch parameter file — the TS reference's per-branch
/// generateKey arguments plus the identity; `%no-protection` is required for
/// an unprotected key, which batch mode otherwise refuses to create.
fn key_parameters(algorithm: Algorithm, name: &str, email: &str, passphrase: Option<&str>) -> String {
    let keys = match algorithm {
        // openpgp.js `type: 'curve25519'` == Ed25519 primary + Curve25519 subkey.
        Algorithm::Ecc => "Key-Type: eddsa\nKey-Curve: ed25519\nKey-Usage: sign,cert\nSubkey-Type: \
                           ecdh\nSubkey-Curve: cv25519\nSubkey-Usage: encrypt\n".to_string(),
        // A literal bit size per branch, like the TS rsaBits ternary.
        other => format!("Key-Type: rsa\nKey-Length: {bits}\nKey-Usage: sign,cert\nSubkey-Type: \
                          rsa\nSubkey-Length: {bits}\nSubkey-Usage: encrypt\n",
            bits = if matches!(other, Algorithm::Rsa4096) { 4096 } else { 2048 }),
    };
    let protection = passphrase.map_or_else(|| "%no-protection\n".into(), |pw| format!("Passphrase: {pw}\n"));
    format!("{keys}Name-Real: {name}\nName-Email: {email}\nExpire-Date: 0\n{protection}%commit\n")
}

/// gpg writes the revocation certificate to `openpgp-revocs.d/<FPR>.rev` at
/// generation time, ':'-commented — uncomment the block as gpg's docs say.
fn revocation_certificate(home: &TempHome, fingerprint: &str) -> Result<String, String> {
    let path = home.0.join(format!("openpgp-revocs.d/{}.rev", fingerprint.to_ascii_uppercase()));
    let mut out = String::new();
    for line in fs::read_to_string(&path).map_err(|e| e.to_string())?.lines() {
        let line = line.strip_prefix(':').map_or(line, |l| l.trim_start());
        if out.is_empty() && !line.starts_with("-----BEGIN PGP PUBLIC KEY BLOCK-----") { continue; }
        out.push_str(line); out.push('\n');
        if line.starts_with("-----END PGP PUBLIC KEY BLOCK-----") { return Ok(out); }
    }
    Err("gpg wrote no revocation certificate".into())
}

/// Generate an ASCII-armored PGP key pair. ECC (Curve25519) is fast; RSA-4096
/// can take a few seconds. `passphrase` encrypts the private key (None/Some("")
/// both mean unprotected, mirroring the TS `passphrase ? : undefined` ternary).
pub fn generate_pgp_key_pair(
    name: &str, email: &str, passphrase: Option<&str>, algorithm: Algorithm,
) -> Result<KeyPair, String> {
    validate_key_gen_identity(name, email)?;
    let (name, email) = (name.trim(), email.trim());
    for field in [name, email] { assert_safe_field(field)?; }
    let passphrase = passphrase.filter(|p| !p.is_empty());
    if let Some(pw) = passphrase { assert_safe_field(pw)?; }
    let home = TempHome::new()?;
    home.gpg(&["--gen-key"], &key_parameters(algorithm, name, email, passphrase), None)?;
    // The fresh key's v4 fingerprint: first `fpr` record (field 10) of a colons listing.
    let fpr = home.gpg(&["--list-keys", "--with-colons"], "", None)?.lines()
        .find(|l| l.starts_with("fpr:")).and_then(|l| l.split(':').nth(9))
        .map(|fpr| fpr.to_ascii_lowercase()).ok_or("gpg listed no fingerprint")?;
    Ok(KeyPair {
        public_key: home.gpg(&["--armor", "--export", &fpr], "", passphrase)?,
        private_key: home.gpg(&["--armor", "--export-secret-keys", &fpr], "", passphrase)?,
        fingerprint: fpr.clone(), revocation_certificate: revocation_certificate(&home, &fpr)?,
    })
}

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 →