Skip to content

Text Encryptor — PHP source

Encrypt or decrypt text with a password using AES-256-GCM. Share the ciphertext safely - only someone with the password can read it.

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

<?php
/**
 * text-encryptor — password-based text encryption (AES-256-GCM + PBKDF2).
 *
 * Language: PHP 7.4+ (standard library only; the bundled ext/openssl).
 * CosmoDev polyglot showcase port of the `text-encryptor` tool, ported from
 * src/lib/text-encryptor.ts (the canonical TypeScript implementation).
 *
 * Why this file exists: PHP ships PBKDF2 (hash_pbkdf2) and AES-256-GCM
 * (openssl_encrypt with the bundled OpenSSL build) in the standard library, so
 * the WebCrypto pipeline ports to a thin, faithful wrapper — salt + IV +
 * ciphertext + 16-byte GCM tag are packed the same way and Base64 output is
 * byte-compatible with the TypeScript original.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

const TE_PBKDF2_ITERATIONS = 100000;
const TE_SALT_BYTES = 16;
const TE_IV_BYTES = 12;
const TE_TAG_BYTES = 16;
// Smallest valid packed payload: salt + IV + one AES-GCM block (tag).
const TE_MIN_BYTES = TE_SALT_BYTES + TE_IV_BYTES + TE_TAG_BYTES;
const TE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

/**
 * PBKDF2-SHA256 (100k iterations) -> 32-byte AES-256 key (raw bytes).
 */
function te_derive_key(string $password, string $salt): string
{
    return hash_pbkdf2('sha256', $password, $salt, TE_PBKDF2_ITERATIONS, 32, true);
}

/**
 * Base64 -> bytes. Accepts surrounding whitespace; throws on any other
 * non-alphabet character, wrong length, or misplaced padding.
 *
 * @throws RuntimeException
 */
function te_base64_to_bytes(string $b64): string
{
    $clean = (string) preg_replace('/\s+/', '', $b64);
    if ($clean === '') {
        throw new RuntimeException('Invalid Base64: input is empty');
    }
    if (strlen($clean) % 4 !== 0) {
        throw new RuntimeException('Invalid Base64: length must be a multiple of 4');
    }
    if (preg_match('/^[A-Za-z0-9+\/]+={0,2}$/', $clean) !== 1) {
        $bad = '?';
        foreach (str_split($clean) as $char) {
            if (strpos(TE_ALPHABET, $char) === false && $char !== '=') {
                $bad = $char;
                break;
            }
        }
        throw new RuntimeException(sprintf('Invalid Base64: unexpected character "%s"', $bad));
    }
    $bytes = base64_decode($clean, true);
    if ($bytes === false) {
        throw new RuntimeException('Invalid Base64: misplaced padding');
    }
    return $bytes;
}

/**
 * Encrypt UTF-8 $plaintext under $password and return the Base64 string
 * packing salt + IV + AES-256-GCM ciphertext (+ tag). Throws if either input
 * is empty.
 *
 * @throws RuntimeException
 */
function encrypt_text(string $plaintext, string $password): string
{
    if ($plaintext === '') {
        throw new RuntimeException('Nothing to encrypt: input is empty');
    }
    if ($password === '') {
        throw new RuntimeException('Password must not be empty');
    }
    $salt = random_bytes(TE_SALT_BYTES);
    $iv = random_bytes(TE_IV_BYTES);
    $key = te_derive_key($password, $salt);

    // GCM mode splits the output: ciphertext from the return value, the
    // 16-byte authentication tag via the by-reference $tag parameter.
    $tag = '';
    $ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
    if ($ciphertext === false) {
        throw new RuntimeException('Encryption failed');
    }

    return base64_encode($salt . $iv . $ciphertext . $tag);
}

/**
 * Decrypt a Base64 string produced by encrypt_text() back to plaintext. Throws
 * on empty input/password, invalid Base64, a payload too short to be one of
 * ours, or a GCM authentication failure (wrong password / tampered data).
 *
 * @throws RuntimeException
 */
function decrypt_text(string $ciphertext, string $password): string
{
    if (trim($ciphertext) === '') {
        throw new RuntimeException('Nothing to decrypt: input is empty');
    }
    if ($password === '') {
        throw new RuntimeException('Password must not be empty');
    }
    $packed = te_base64_to_bytes(trim($ciphertext));
    if (strlen($packed) < TE_MIN_BYTES) {
        throw new RuntimeException('Ciphertext too short - not a valid salt + IV + AES-GCM payload');
    }

    $salt = substr($packed, 0, TE_SALT_BYTES);
    $iv = substr($packed, TE_SALT_BYTES, TE_IV_BYTES);
    $body = substr($packed, TE_SALT_BYTES + TE_IV_BYTES);
    $tag = substr($body, -TE_TAG_BYTES);
    $data = substr($body, 0, strlen($body) - TE_TAG_BYTES);

    $key = te_derive_key($password, $salt);
    $plaintext = openssl_decrypt($data, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag);
    if ($plaintext === false) {
        // openssl_decrypt returns false when GCM tag verification fails.
        throw new RuntimeException('Decryption failed - wrong password or corrupted ciphertext');
    }

    return $plaintext;
}

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 →