Skip to content

PGP Encrypt & Decrypt — JavaScript source

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

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

/**
 * pgp-encrypt — read OpenPGP key metadata, encrypt (optionally signing), decrypt.
 *
 * Language: JavaScript (ES module; Node >= 16, Bun, Deno — no imports, no npm dependencies).
 * CosmoDev polyglot showcase port of the `pgp-encrypt` tool, ported from
 * src/lib/pgp-encrypt.ts (the canonical TypeScript implementation).
 *
 * The TS reference leans on openpgp.js; no JS runtime ships an OpenPGP
 * implementation, so this port drives the `gpg` binary — the engine the C port
 * reaches through GPGME — with argv arrays over stdin/stdout, inside a fresh
 * 0700 GNUPGHOME deleted on the way out (nothing touches the real keyring).
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

// gpg numeric public-key algorithm ids -> openpgp.js-style names.
const ALGO_NAMES = {
  1: 'rsa', 2: 'rsa', 3: 'rsa', 16: 'elgamal', 17: 'dsa',
  18: 'ecdh', 19: 'ecdsa', 22: 'ed25519', 27: 'x25519',
};

// Mirror the TS port's empty-input Error contract.
const must = (value, message) => { if (!value) throw new Error(message); };

// gpg escapes non-printable userid bytes as \xNN; decode them back to text.
const unescapeUid = (uid) =>
  uid.replace(/\\x([0-9a-fA-F]{2})/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));

// Parse the first primary key out of `gpg --with-colons` output. Fields:
// pub[3]=algo [5]=creation [6]=expiry (epoch secs); fpr[9]=fingerprint; uid[9]=user id.
function primaryKey(colons) {
  let pub, fpr, uid;
  for (const line of colons.split('\n')) {
    const f = line.split(':');
    if (f[0] === 'pub' && !pub) pub = f;
    if (f[0] === 'fpr' && !fpr) fpr = f[9];
    if (f[0] === 'uid' && !uid) uid = unescapeUid(f[9]);
  }
  if (!pub || !fpr) throw new Error('unrecognized key format');
  const iso = (sec) => new Date(Number(sec) * 1000).toISOString().slice(0, 10);
  return {
    userID: uid || 'unknown',
    fingerprint: fpr.toUpperCase(),
    algorithm: ALGO_NAMES[pub[3]] ?? `algo-${pub[3]}`,
    creationDate: iso(pub[5]),
    expiry: pub[6] ? iso(pub[6]) : null,
  };
}

// Run gpg inside an ephemeral 0700 GNUPGHOME under a temp dir deleted on the
// way out. gpg always gets an argument ARRAY, never a command string, so no
// key, message or passphrase is ever parsed by a shell.
async function withTempHome(run) {
  const { mkdtempSync, rmSync, chmodSync } = await import('node:fs');
  const { join } = await import('node:path');
  const { tmpdir } = await import('node:os');
  const { spawnSync } = await import('node:child_process');
  const home = mkdtempSync(join(tmpdir(), 'gnupg-'));
  chmodSync(home, 0o700); // gpg refuses a world-readable home.
  try {
    return await run((args, input = '') => {
      const r = spawnSync('gpg', ['--homedir', home, '--batch', '--yes', ...args],
        { input, encoding: 'utf8' });
      if (r.error) throw r.error;
      if (r.status !== 0) throw new Error((r.stderr || `gpg exited with status ${r.status}`).trim());
      return r.stdout;
    });
  } finally {
    rmSync(home, { recursive: true, force: true });
  }
}

// Import one armored key; --import-options import-show lists exactly what was
// imported, so the fingerprint is always the just-imported key.
const importKey = async (gpg, armored) =>
  primaryKey(gpg(['--import-options', 'import-show', '--with-colons', '--import'], armored)).fingerprint;

/** Read a PGP key (public or private); throws on empty or invalid input. */
export async function readKeyInfo(armoredKey) {
  must(armoredKey, 'Key input is empty or invalid.');
  const trimmed = armoredKey.trim();
  const isPrivate =
    trimmed.includes('-----BEGIN PGP PRIVATE KEY BLOCK-----') ||
    trimmed.includes('-----BEGIN PGP SECRET KEY BLOCK-----');
  try {
    return await withTempHome(async (gpg) => {
      await gpg(['--import'], trimmed);
      return { isPrivate, ...primaryKey(await gpg(['--with-colons', '--list-keys'])) };
    });
  } catch (e) {
    throw new Error(`Invalid PGP key: ${e instanceof Error ? e.message : 'unrecognized key format'}`);
  }
}

/** Encrypt for a recipient's public key; optionally sign with the sender's. */
export async function pgpEncrypt(message, publicKeyArmored, signingPrivateKeyArmored, passphrase) {
  must(message, 'Message must not be empty.');
  must(publicKeyArmored, 'Recipient public key must not be empty.');
  return withTempHome(async (gpg) => {
    const args = ['--armor', '--recipient', await importKey(gpg, publicKeyArmored.trim()), '--encrypt'];
    if (signingPrivateKeyArmored) {
      args.push('--sign', '--local-user', await importKey(gpg, signingPrivateKeyArmored.trim()),
        '--pinentry-mode', 'loopback');
      if (passphrase) args.push('--passphrase', passphrase);
    }
    return gpg(args, message);
  });
}

/** Decrypt an armored message with the recipient's private key. */
export async function pgpDecrypt(armoredMessage, privateKeyArmored, passphrase) {
  must(armoredMessage, 'Armored message must not be empty.');
  must(privateKeyArmored, 'Private key must not be empty.');
  return withTempHome(async (gpg) => {
    await importKey(gpg, privateKeyArmored.trim());
    const args = ['--pinentry-mode', 'loopback', '--decrypt'];
    if (passphrase) args.push('--passphrase', passphrase);
    return gpg(args, armoredMessage.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 →