Skip to content

PGP Encrypt & Decrypt — PHP source

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

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

<?php
/**
 * pgp-encrypt — read OpenPGP key metadata, encrypt (optionally signing), decrypt.
 *
 * Language: PHP 7.4+ (standard library only — proc_open drives the `gpg`
 *           binary, the same engine the C port reaches through GPGME and the
 *           native counterpart to the TS reference's openpgp.js).
 * CosmoDev polyglot showcase port of the `pgp-encrypt` tool, ported from
 * src/lib/pgp-encrypt.ts (the canonical TypeScript implementation).
 *
 * gpg is always spawned with an argument ARRAY (proc_open, never a command
 * string), so no key, message or passphrase is ever parsed by a shell, and
 * armored keys are imported into a fresh 0700 GNUPGHOME under a temp dir that
 * is deleted on the way out — nothing touches the user's real keyring.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

// gpg numeric public-key algorithm ids -> openpgp.js-style names.
const PGP_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. */
function pgp_must($value, string $message): void
{
    if (!$value) {
        throw new InvalidArgumentException($message);
    }
}

/** Run gpg inside $home; argument array, never a shell.
 * @throws RuntimeException when gpg exits non-zero. */
function pgp_run(string $home, array $args, string $stdin = ''): string
{
    $proc = proc_open(
        array_merge(['gpg', '--homedir', $home, '--batch', '--yes'], $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], $stdin);
    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_with_temp_home(callable $fn)
{
    $home = sys_get_temp_dir() . '/gnupg-' . 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('unlink', glob("$home/*") ?: []); // best-effort cleanup
        @rmdir($home);
    }
}

/** Parse the first primary key out of `gpg --with-colons` output. Fields:
 * pub[3]=algo [5]=creation [6]=expiry (epoch secs); fpr[9]=fpr; uid[9]=user id.
 * Returns the PGPKeyInfo shape: userID, fingerprint, algorithm,
 * creationDate (ISO yyyy-MM-dd), expiry (ISO or null when never), isPrivate. */
function pgp_primary(string $colons): array
{
    $pub = $fpr = $uid = null;
    foreach (explode("\n", $colons) as $line) {
        $f = explode(':', $line);
        if ($f[0] === 'pub' && $pub === null) {
            $pub = $f;
        } elseif ($f[0] === 'fpr' && $fpr === null) {
            $fpr = $f[9];
        } elseif ($f[0] === 'uid' && $uid === null) {
            // gpg escapes non-printable userid bytes as \xNN; decode them back.
            $uid = preg_replace_callback('/\\\\x([0-9a-fA-F]{2})/', fn ($m) => chr(hexdec($m[1])), $f[9]);
        }
    }
    if ($pub === null || $fpr === null) {
        throw new RuntimeException('unrecognized key format');
    }
    $iso = fn (string $sec): string => gmdate('Y-m-d', (int) $sec); // UTC, as toISOString().

    return [
        'userID' => $uid !== null && $uid !== '' ? $uid : 'unknown',
        'fingerprint' => strtoupper($fpr),
        'algorithm' => PGP_ALGO_NAMES[(int) $pub[3]] ?? "algo-{$pub[3]}",
        'creationDate' => $iso($pub[5]),
        'expiry' => $pub[6] !== '' ? $iso($pub[6]) : null,
    ];
}

/** Import one armored key, returning its fingerprint (--import-options
 * import-show lists exactly what was imported, so it is always that key). */
function pgp_import(string $home, string $armored): string
{
    $shown = pgp_run($home, ['--import-options', 'import-show', '--with-colons', '--import'], $armored);

    return pgp_primary($shown)['fingerprint'];
}

/** Read a PGP key (public or private); RuntimeException on invalid input. */
function pgp_read_key_info(string $armoredKey): array
{
    pgp_must($armoredKey, 'Key input is empty or invalid.');
    $trimmed = trim($armoredKey);
    $isPrivate = strpos($trimmed, '-----BEGIN PGP PRIVATE KEY BLOCK-----') !== false
        || strpos($trimmed, '-----BEGIN PGP SECRET KEY BLOCK-----') !== false;
    try {
        return pgp_with_temp_home(function (string $home) use ($trimmed, $isPrivate): array {
            pgp_run($home, ['--import'], $trimmed);

            return array_merge(
                ['isPrivate' => $isPrivate],
                pgp_primary(pgp_run($home, ['--with-colons', '--list-keys']))
            );
        });
    } catch (RuntimeException $e) {
        throw new RuntimeException('Invalid PGP key: ' . $e->getMessage());
    }
}

/** Encrypt a plaintext message for a recipient's public key, optionally signed
 * with the sender's private key; returns an ASCII-armored PGP message. */
function pgp_encrypt(string $message, string $publicKeyArmored, ?string $signingPrivateKeyArmored = null, ?string $passphrase = null): string
{
    pgp_must($message, 'Message must not be empty.');
    pgp_must($publicKeyArmored, 'Recipient public key must not be empty.');

    return pgp_with_temp_home(function (string $home) use ($message, $publicKeyArmored, $signingPrivateKeyArmored, $passphrase): string {
        $args = ['--armor', '--recipient', pgp_import($home, trim($publicKeyArmored)), '--encrypt'];
        if ($signingPrivateKeyArmored !== null) {
            array_push($args, '--sign', '--local-user', pgp_import($home, trim($signingPrivateKeyArmored)), '--pinentry-mode', 'loopback');
            if ($passphrase !== null) {
                array_push($args, '--passphrase', $passphrase);
            }
        }

        return pgp_run($home, $args, $message);
    });
}

/** Decrypt an ASCII-armored PGP message with the recipient's private key. */
function pgp_decrypt(string $armoredMessage, string $privateKeyArmored, ?string $passphrase = null): string
{
    pgp_must($armoredMessage, 'Armored message must not be empty.');
    pgp_must($privateKeyArmored, 'Private key must not be empty.');

    return pgp_with_temp_home(function (string $home) use ($armoredMessage, $privateKeyArmored, $passphrase): string {
        pgp_import($home, trim($privateKeyArmored));
        $args = ['--pinentry-mode', 'loopback', '--decrypt'];
        if ($passphrase !== null) {
            array_push($args, '--passphrase', $passphrase);
        }

        return pgp_run($home, $args, trim($armoredMessage));
    });
}

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 →