Skip to content

PGP Encrypt & Decrypt — Rust source

Encrypt or decrypt messages with PGP public/private keys. Powered by OpenPGP.js, runs entirely in your browser.

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

//! pgp-encrypt — read OpenPGP key metadata, encrypt (optionally signing), decrypt.
//!
//! Language: Rust (std only — std::process::Command drives the `gpg` binary,
//! the same engine the C port reaches through GPGME and the native counterpart
//! to the TS reference's openpgp.js; std.crypto has no OpenPGP implementation).
//! CosmoDev polyglot showcase port of the `pgp-encrypt` tool, ported from
//! src/lib/pgp-encrypt.ts (the canonical TypeScript implementation).
//!
//! gpg always takes an argv VECTOR, never a shell, and armored keys are
//! imported into a fresh 0700 GNUPGHOME deleted on the way out, so nothing
//! touches the user's real keyring. Err(String) mirrors the TS port's throws.
//!
//! display source — part of CosmoDev's polyglot tool pages.

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

/// One armored PGP key's metadata (PGPKeyInfo in the TS reference).
pub struct PGPKeyInfo {
    pub user_id: String,
    pub fingerprint: String,
    pub algorithm: String,
    /// ISO yyyy-MM-dd.
    pub creation_date: String,
    /// ISO yyyy-MM-dd, None when the key never expires.
    pub expiry: Option<String>,
    pub is_private: bool,
}

/// gpg numeric public-key algorithm ids -> openpgp.js-style names.
fn algo_name(id: u32) -> String {
    match id {
        1 | 2 | 3 => "rsa",
        16 => "elgamal",
        17 => "dsa",
        18 => "ecdh",
        19 => "ecdsa",
        22 => "ed25519",
        27 => "x25519",
        other => return format!("algo-{other}"),
    }
    .to_string()
}

/// Epoch seconds -> ISO yyyy-MM-dd (UTC) — the role toISOString() plays in
/// the TS port. Howard Hinnant's civil_from_days: days since 1970-01-01 -> y/m/d.
fn iso_date(epoch_secs: i64) -> String {
    let z = epoch_secs.div_euclid(86_400) + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097; // [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11]
    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
    format!("{:04}-{:02}-{:02}", y + i64::from(m <= 2), m, d)
}

/// Decode gpg's \xNN escapes in a userid back to characters.
fn unescape_uid(uid: &str) -> String {
    let (b, mut out, mut i) = (uid.as_bytes(), String::new(), 0);
    while i < b.len() {
        if i + 4 <= b.len() && b[i] == b'\\' && b[i + 1] == b'x'
            && b[i + 2].is_ascii_hexdigit() && b[i + 3].is_ascii_hexdigit() {
            out.push(u8::from_str_radix(&uid[i + 2..i + 4], 16).unwrap() as char);
            i += 4;
        } else {
            let c = uid[i..].chars().next().unwrap();
            out.push(c);
            i += c.len_utf8();
        }
    }
    out
}

/// A fresh 0700 GNUPGHOME under a temp dir, deleted on drop, so no key ever
/// touches the user's real keyring (gpg refuses world-readable homes).
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-{}", 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 with this home; argv vector, never a shell; stdin in, stdout out.
    fn gpg(&self, args: &[&str], stdin: &str) -> Result<String, String> {
        let mut child = Command::new("gpg").arg("--homedir").arg(&self.0)
            .args(["--batch", "--yes"]).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() {
            String::from_utf8(out.stdout).map_err(|_| "gpg emitted non-UTF-8 output".into())
        } else {
            Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
        }
    }
}

/// First primary key in `gpg --with-colons` output: fingerprint, algo id,
/// creation epoch, expiry ("" when never), first user ID. Fields: pub[3]/[5]/[6],
/// fpr[9], uid[9].
fn primary(colons: &str) -> Result<(String, u32, i64, String, String), String> {
    let (mut pub_, mut fpr, mut uid) = (None, None, None);
    for line in colons.lines() {
        let f: Vec<&str> = line.split(':').collect();
        match f[0] {
            "pub" if pub_.is_none() => pub_ = Some((f[3].to_string(), f[5].to_string(), f[6].to_string())),
            "fpr" if fpr.is_none() => fpr = Some(f[9].to_string()),
            "uid" if uid.is_none() => uid = Some(unescape_uid(f[9])),
            _ => {}
        }
    }
    match pub_ {
        Some((algo, created, expiry)) if fpr.is_some() => Ok((
            fpr.unwrap(),
            algo.parse().unwrap_or(0),
            created.parse().unwrap_or(0),
            expiry,
            uid.unwrap_or_else(|| "unknown".into()),
        )),
        _ => Err("unrecognized key format".into()),
    }
}

/// Import one armored key, returning its fingerprint (--import-options
/// import-show lists exactly what was imported, so it is always that key).
fn import_fpr(home: &TempHome, armored: &str) -> Result<String, String> {
    let shown = home.gpg(&["--import-options", "import-show", "--with-colons", "--import"], armored)?;
    primary(&shown).map(|(fpr, ..)| fpr)
}

/// Read a PGP key (public or private) and extract its metadata; Err on empty
/// input or unrecognized key material, wrapped in the TS port's "Invalid PGP
/// key" contract.
pub fn read_key_info(armored_key: &str) -> Result<PGPKeyInfo, String> {
    let trimmed = armored_key.trim();
    if trimmed.is_empty() {
        return Err("Key input is empty or invalid.".into());
    }
    let is_private = trimmed.contains("-----BEGIN PGP PRIVATE KEY BLOCK-----")
        || trimmed.contains("-----BEGIN PGP SECRET KEY BLOCK-----");
    let run = || -> Result<PGPKeyInfo, String> {
        let home = TempHome::new()?;
        let shown = home.gpg(&["--import-options", "import-show", "--with-colons", "--import"], trimmed)?;
        let (fpr, algo, created, expiry, uid) = primary(&shown)?;
        Ok(PGPKeyInfo {
            fingerprint: fpr.to_uppercase(),
            algorithm: algo_name(algo),
            creation_date: iso_date(created),
            expiry: (!expiry.is_empty()).then(|| iso_date(expiry.parse().unwrap_or(0))),
            user_id: uid,
            is_private,
        })
    };
    run().map_err(|e| format!("Invalid PGP key: {e}"))
}

/// Encrypt a plaintext message for a recipient's public key; optionally sign
/// with the sender's private key (signing_private_key_armored + passphrase).
/// Returns an ASCII-armored PGP message.
pub fn pgp_encrypt(
    message: &str,
    public_key_armored: &str,
    signing_private_key_armored: Option<&str>,
    passphrase: Option<&str>,
) -> Result<String, String> {
    if message.is_empty() { return Err("Message must not be empty.".into()); }
    if public_key_armored.is_empty() { return Err("Recipient public key must not be empty.".into()); }
    let home = TempHome::new()?;
    let recipient = import_fpr(&home, public_key_armored.trim())?;
    let signer = match signing_private_key_armored {
        Some(sk) => Some(import_fpr(&home, sk.trim())?),
        None => None,
    };
    let mut args = vec!["--armor", "--recipient", recipient.as_str(), "--encrypt"];
    if let Some(s) = &signer {
        args.extend(["--sign", "--local-user", s.as_str(), "--pinentry-mode", "loopback"]);
        if let Some(pw) = passphrase {
            args.push("--passphrase");
            args.push(pw);
        }
    }
    home.gpg(&args, message)
}

/// Decrypt an ASCII-armored PGP message with the recipient's private key.
pub fn pgp_decrypt(armored_message: &str, private_key_armored: &str, passphrase: Option<&str>) -> Result<String, String> {
    if armored_message.is_empty() { return Err("Armored message must not be empty.".into()); }
    if private_key_armored.is_empty() { return Err("Private key must not be empty.".into()); }
    let home = TempHome::new()?;
    import_fpr(&home, private_key_armored.trim())?;
    let mut args = vec!["--pinentry-mode", "loopback", "--decrypt"];
    if let Some(pw) = passphrase {
        args.push("--passphrase");
        args.push(pw);
    }
    home.gpg(&args, armored_message.trim())
}

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 →