PGP Key Generator — JavaScript source
Generate PGP key pairs (ECC or RSA) in your browser. Download your public and private keys. Powered by OpenPGP.js.
This is the JavaScript 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: JavaScript (ES2022; WebCrypto globals only - browsers, Node >= 22,
* Bun, Deno. No imports, no dependencies).
* 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`; this port keeps the same
* public API and output shape but builds the OpenPGP (RFC 4880/9580) packets
* directly on WebCrypto primitives - the substitution every sibling port here
* makes, taken to its zero-dependency extreme: Ed25519 keys for 'ecc', RSA for
* 'rsa2048'/'rsa4096', a certification self-signature, and a revocation
* certificate all come from the same small packet machinery. Two deliberate
* gaps vs the reference, noted inline: passphrase-protected secret keys need
* OpenPGP's S2K schedule plus AES-CFB, neither of which WebCrypto exposes, so
* a passphrase is rejected up front rather than silently producing an
* unprotected key; and 'ecc' yields a sign-capable Ed25519 primary, like the
* gpg-driven sibling ports.
*
* display source - part of CosmoDev's polyglot tool pages.
*/
// Mirrors EMAIL_RE in the TS reference: one @, non-empty local + domain with a dot.
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const encoder = new TextEncoder();
/** Validate the identity that goes into the key's user ID. Throws on invalid input. */
export function validateKeyGenIdentity(name, email) {
if (!name.trim()) throw new Error('Name is required.');
if (!email.trim()) throw new Error('Email is required.');
if (!EMAIL_RE.test(email.trim())) throw new Error('Invalid email address.');
}
// --- wire-format helpers (RFC 4880) ------------------------------------------
const u16 = (n) => new Uint8Array([(n >>> 8) & 255, n & 255]);
const u32 = (n) => new Uint8Array([(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]);
const cat = (...parts) => {
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
let at = 0;
for (const part of parts) { out.set(part, at); at += part.length; }
return out;
};
/** JWK base64url -> octets. */
const b64uToBytes = (s) => Uint8Array.from(atob(s.replaceAll('-', '+').replaceAll('_', '/')), (c) => c.charCodeAt(0));
/** JWK base64url -> BigInt. */
const b64uToBig = (s) => BigInt('0x' + [...b64uToBytes(s)].map((b) => b.toString(16).padStart(2, '0')).join(''));
/** BigInt -> minimal big-endian octets. */
const bigToBytes = (v) => {
let hex = v.toString(16);
if (hex.length & 1) hex = '0' + hex;
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(2 * i, 2 * i + 2), 16);
return out;
};
/** Multiprecision integer: 16-bit bit count + minimal big-endian octets. */
const mpi = (bytes) => {
let start = 0;
while (start < bytes.length && bytes[start] === 0) start++;
const body = bytes.subarray(start);
const bits = body.length ? (body.length - 1) * 8 + (31 - Math.clz32(body[0])) : 0;
return cat(u16(bits), body);
};
/** New-format packet: tag with the high bits set, then a 1/2/5-octet length. */
const packet = (tag, body) => {
let len;
if (body.length < 192) len = new Uint8Array([body.length]);
else if (body.length < 8384) { const n = body.length - 192; len = new Uint8Array([(n >>> 8) + 192, n & 255]); }
else len = cat(new Uint8Array([255]), u32(body.length));
return cat(new Uint8Array([0xc0 | tag]), len, body);
};
/** CRC-24 (RFC 4880 section 6.1) over an armor body. */
const crc24 = (bytes) => {
let crc = 0xb704ce;
for (const b of bytes) {
crc ^= b << 16;
for (let bit = 0; bit < 8; bit++) { crc <<= 1; if (crc & 0x1000000) crc ^= 0x1864cfb; }
}
return crc & 0xffffff;
};
/** ASCII armor: header, optional Comment, 64-column base64, `=CRC24` trailer. */
const armor = (body, comment) => {
let binary = '';
for (const b of body) binary += String.fromCharCode(b);
const crc = crc24(body);
const base64 = btoa(binary).replace(/(.{64})/g, '$1\n').replace(/\n$/, '');
const checksum = btoa(String.fromCharCode((crc >> 16) & 255, (crc >> 8) & 255, crc & 255));
return ['-----BEGIN PGP PUBLIC KEY BLOCK-----', ...(comment ? [`Comment: ${comment}`] : []),
'', base64, `=${checksum}`, '-----END PGP PUBLIC KEY BLOCK-----', ''].join('\n');
};
// --- packet assembly ----------------------------------------------------------
// The Ed25519 curve OID (1.3.6.1.4.1.11591.15.1), MPI-wrapped (RFC 9580 section 9.2).
const ED25519_OID = mpi(new Uint8Array([0x2b, 0x06, 0x01, 0x04, 0x01, 0xda, 0x47, 0x0f, 0x01]));
/** Version-4 public key body: version, creation time, algorithm, algorithm material. */
const publicKeyBody = (algo, created, material) =>
cat(new Uint8Array([4]), u32(created), new Uint8Array([algo]), ...material);
/** Version-4 secret key body: public fields, S2K usage 0 (unprotected), secret MPIs, 16-bit checksum. */
const secretKeyBody = (pub, secretMPIs) => {
const secret = cat(...secretMPIs);
let sum = 0;
for (const b of secret) sum = (sum + b) & 0xffff;
return cat(pub, new Uint8Array([0]), secret, u16(sum));
};
/** Version-4 signature packet body over `document`, signed with the new private key. */
const signatureBody = async (key, keyAlgo, sigType, document, created, fingerprint) => {
const creation = cat(new Uint8Array([5, 2]), u32(created)); // signature creation time
const issuer = cat(new Uint8Array([22, 33, 4]), fingerprint); // issuer fingerprint (04 + 20 octets)
const subpackets = cat(creation, issuer);
const hashed = cat(u16(subpackets.length), subpackets); // length excludes the two length octets
const signed = cat(document, new Uint8Array([4, sigType, keyAlgo, 8]), hashed,
u16(0), new Uint8Array([4, 255]), u32(document.length));
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', signed)); // left 16 bits of the hash
const raw = keyAlgo === 22
? new Uint8Array(await crypto.subtle.sign('Ed25519', key, signed)) // PureEdDSA over the signed data
: new Uint8Array(await crypto.subtle.sign({ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, key, signed));
return cat(new Uint8Array([4, sigType, keyAlgo, 8]), hashed, u16(0), digest.slice(0, 2), mpi(raw));
};
/** v4 fingerprint: SHA-1 over 0x99, the body length, and the public key body. */
const fingerprintOf = async (body) => {
const digest = new Uint8Array(await crypto.subtle.digest('SHA-1', cat(new Uint8Array([0x99]), u16(body.length), body)));
return [...digest].map((b) => b.toString(16).padStart(2, '0')).join('');
};
/**
* Generate an ASCII-armored PGP key pair. ECC (Ed25519, the Curve25519 family)
* is fast; RSA-4096 can take a few seconds. Returns the TypeScript reference's
* exact output shape: publicKey, privateKey, fingerprint (40 lowercase hex
* chars) and revocationCertificate.
*
* @throws {Error} on an invalid identity, an unsupported algorithm, or a
* passphrase (see the header note on S2K + AES-CFB).
*/
export async function generatePGPKeyPair({ name, email, passphrase, algorithm = 'ecc' }) {
validateKeyGenIdentity(name, email);
if (passphrase) throw new Error('Passphrase protection is not available in the WebCrypto port; pass no passphrase.');
if (algorithm !== 'ecc' && algorithm !== 'rsa2048' && algorithm !== 'rsa4096') {
throw new Error(`Unsupported algorithm: ${algorithm}`);
}
const created = Math.floor(Date.now() / 1000);
let keyAlgo, privKey, publicMaterial, secretMaterial;
if (algorithm === 'ecc') {
const pair = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign']);
privKey = pair.privateKey;
keyAlgo = 22; // Ed25519 (EdDSA), as the gpg-driven sibling ports generate
publicMaterial = [ED25519_OID, mpi(b64uToBytes(await crypto.subtle.exportKey('jwk', pair.publicKey).then((j) => j.x)))];
secretMaterial = [mpi(b64uToBytes((await crypto.subtle.exportKey('jwk', privKey)).d))];
} else {
const pair = await crypto.subtle.generateKey({
name: 'RSASSA-PKCS1-v1_5', modulusLength: algorithm === 'rsa4096' ? 4096 : 2048,
publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256',
}, true, ['sign']);
privKey = pair.privateKey;
const jwk = await crypto.subtle.exportKey('jwk', privKey);
keyAlgo = 1; // RSA (sign + encrypt), matching openpgp.js RSA keys
publicMaterial = [mpi(bigToBytes(b64uToBig(jwk.n))), mpi(bigToBytes(b64uToBig(jwk.e)))];
// Secret MPIs: d, p, q, u = p^-1 mod q - exactly the JWK's CRT fields.
secretMaterial = [jwk.d, jwk.p, jwk.q, jwk.qi].map((v) => mpi(bigToBytes(b64uToBig(v))));
}
const body = publicKeyBody(keyAlgo, created, publicMaterial);
const fingerprint = await fingerprintOf(body);
const fpBytes = new Uint8Array(20);
for (let i = 0; i < 20; i++) fpBytes[i] = parseInt(fingerprint.slice(2 * i, 2 * i + 2), 16);
const uid = packet(13, encoder.encode(`${name.trim()} <${email.trim()}>`));
const cert = await signatureBody(privKey, keyAlgo, 0x13, cat(body, uid), created, fpBytes);
const revocation = await signatureBody(privKey, keyAlgo, 0x20, body, created, fpBytes);
return {
publicKey: armor(cat(packet(6, body), uid, packet(2, cert))),
privateKey: armor(cat(packet(5, secretKeyBody(body, secretMaterial)), uid, packet(2, cert))),
fingerprint,
revocationCertificate: armor(packet(2, revocation), 'Revocation certificate'),
};
}
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 →