Skip to content

PGP Key Generator — PHP source

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

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

<?php
/**
 * pgp-keygen — ASCII-armored OpenPGP key pair generation (ECC Curve25519,
 * RSA-2048, RSA-4096) with a v4 fingerprint and a revocation certificate.
 *
 * Language: PHP 7.4+ (standard library only — proc_open drives the `gpg`
 *           binary, the same engine the sibling C/Ruby ports shell out to and
 *           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 is always spawned with an argument ARRAY (proc_open, never a command
 * string), so no identity or passphrase is ever parsed by a shell, and every
 * key is generated in a fresh 0700 GNUPGHOME deleted on the way out — the
 * passphrase (an empty line for the unprotected case) is fed on stdin via
 * --passphrase-fd 0 with loopback pinentry, the Python sibling's trick.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

// Mirrors EMAIL_RE in the TS reference: one @, non-empty local + domain with a dot.
const PGP_KEYGEN_EMAIL_RE = '/^[^\s@]+@[^\s@]+\.[^\s@]+$/';

// Algorithm choices, mirroring PGPKeyGenAlgorithm in the TS reference. gpg's
// 'ed25519' = Ed25519 primary + Curve25519 encryption subkey, the TS 'ecc' family.
const PGP_KEYGEN_ALGORITHMS = ['ecc' => 'ed25519', 'rsa2048' => 'rsa2048', 'rsa4096' => 'rsa4096'];

/** Validate the identity that goes into the key's user ID. Throws on invalid input. */
function pgp_keygen_validate_identity(string $name, string $email): void
{
    if (trim($name) === '') { throw new InvalidArgumentException('Name is required.'); }
    if (trim($email) === '') { throw new InvalidArgumentException('Email is required.'); }
    if (preg_match(PGP_KEYGEN_EMAIL_RE, trim($email)) !== 1) { throw new InvalidArgumentException('Invalid email address.'); }
}

/** Run gpg inside $home; argument array, never a shell.
 * @throws RuntimeException when gpg exits non-zero. */
function pgp_keygen_run(string $home, array $args, ?string $passphrase = null): string
{
    $proc = proc_open(
        array_merge(['gpg', '--homedir', $home, '--batch', '--no-tty', '--yes',
            '--pinentry-mode', 'loopback', '--passphrase-fd', '0'], $args),
        [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
        $pipes
    );
    if (!is_resource($proc)) {
        throw new RuntimeException('Failed to start gpg');
    }
    fwrite($pipes[0], ($passphrase ?? '') . "\n");
    fclose($pipes[0]);
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    if (proc_close($proc) !== 0) {
        throw new RuntimeException(trim($stderr !== '' ? $stderr : 'gpg exited non-zero'));
    }
    return (string) $stdout;
}

/** A fresh 0700 GNUPGHOME under a temp dir, deleted on the way out, so no key
 * ever touches the user's real keyring (gpg refuses world-readable homes). */
function pgp_keygen_with_temp_home(callable $fn)
{
    $home = sys_get_temp_dir() . '/gnupg-keygen-' . bin2hex(random_bytes(8));
    if (!mkdir($home, 0700, true)) {
        throw new RuntimeException('Failed to create a temp GNUPGHOME');
    }
    try {
        return $fn($home);
    } finally {
        array_map(fn ($path) => @unlink($path), glob("$home/*") ?: []); // best-effort cleanup
        @rmdir($home);
    }
}

/** Generate an ASCII-armored PGP key pair (ECC/Curve25519 fast, RSA-4096 slow),
 * returning the TS reference's exact output shape: publicKey, privateKey,
 * fingerprint (40 lowercase hex chars) and revocationCertificate. Only a real
 * passphrase encrypts the private key, as in the TS reference.
 * @throws InvalidArgumentException on an invalid identity or algorithm. */
function pgp_keygen_generate(string $name, string $email, string $algorithm = 'ecc', ?string $passphrase = null): array
{
    pgp_keygen_validate_identity($name, $email);
    if (!isset(PGP_KEYGEN_ALGORITHMS[$algorithm])) {
        throw new InvalidArgumentException("Unsupported algorithm: {$algorithm}");
    }
    // An empty-string passphrase would still encrypt the key; only a real
    // passphrase should (the `pass` guard in the TS reference).
    $secret = $passphrase !== null && $passphrase !== '' ? $passphrase : null;

    return pgp_keygen_with_temp_home(function (string $home) use ($name, $email, $algorithm, $secret): array {
        // EXPIRE 0 = never expires, matching openpgp.js's default.
        pgp_keygen_run($home, array_merge(['--quick-generate-key',
            sprintf('%s <%s>', trim($name), trim($email)), PGP_KEYGEN_ALGORITHMS[$algorithm], 'default', '0']), $secret);
        // The fresh key's v4 fingerprint: first `fpr` record (field 10) of a
        // `--with-colons` listing, lowercase like the TS reference returns.
        $fingerprint = '';
        foreach (explode("\n", pgp_keygen_run($home, ['--list-keys', '--with-colons'])) as $line) {
            if (strpos($line, 'fpr:') === 0) {
                $fingerprint = strtolower(explode(':', $line)[9]);
                break;
            }
        }
        if ($fingerprint === '') {
            throw new RuntimeException('gpg generated no key (no fingerprint record).');
        }
        // gpg writes an armored revocation certificate per key at generation
        // time, under openpgp-revocs.d/<FINGERPRINT>.rev.
        $revPath = $home . '/openpgp-revocs.d/' . strtoupper($fingerprint) . '.rev';
        return [
            'publicKey' => pgp_keygen_run($home, ['--armor', '--export', $fingerprint], $secret),
            'privateKey' => pgp_keygen_run($home, ['--armor', '--export-secret-keys', $fingerprint], $secret),
            'fingerprint' => $fingerprint,
            'revocationCertificate' => is_file($revPath) ? (string) file_get_contents($revPath) : '',
        ];
    });
}

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 →