Skip to content

Argon2 Hash & Verify — PHP source

Hash passwords with Argon2id — the winner of the Password Hashing Competition. Configure memory, iterations, and parallelism. WASM-powered, client-side.

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

<?php
/**
 * argon2 — Argon2id password hashing (PHC parse/format logic in pure PHP;
 * the KDF itself via PHP's native password_hash / password_verify).
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `argon2` tool, ported from
 * src/lib/argon2.ts (the canonical TypeScript implementation).
 *
 * The TS build drives the reference C library compiled to WASM
 * (argon2-browser). PHP is the one polyglot whose standard library has
 * Argon2 built in — password_hash(PASSWORD_ARGON2ID) / password_verify
 * (PHP 7.3+, on builds linked against libargon2; the mainstream default) —
 * so, unlike the JavaScript / Python / Ruby siblings, no CLI detour: only
 * the PHC parser and Base64 codec are hand-ported. PHP generates the
 * 16-byte salt internally and fixes the digest at 32 bytes, so the lib's
 * options['salt'] / options['hashLength'] are rejected rather than
 * silently ignored.
 *
 * PHC string format (what `encoded` holds - the string you store in a DB):
 *   $argon2id$v=19$m=65536,t=3,p=1$<b64 salt>$<b64 digest>
 * Salt and digest are unpadded standard Base64.
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

/** Defaults follow the OWASP-recommended Argon2id profile (64 MiB, 3 passes). */
const ARGON2_DEFAULTS = ['memory' => 65536, 'iterations' => 3, 'parallelism' => 1, 'hashLength' => 32];

/**
 * Unpadded standard Base64 (the PHC encoding) -> raw bytes. Strict mode —
 * base64_decode's second argument — rejects characters outside the alphabet
 * instead of silently dropping them; the '=' padding PHC strips is re-added.
 *
 * @throws \RuntimeException on any malformed input.
 */
function phcBase64ToBytes(string $b64): string
{
    if ($b64 === '' || preg_match('/^[A-Za-z0-9\/+]+$/', $b64) !== 1 || strlen($b64) % 4 === 1) {
        throw new RuntimeException('Invalid Argon2 string: empty / non-Base64 / impossible length');
    }
    $bytes = base64_decode($b64 . str_repeat('=', (4 - strlen($b64) % 4) % 4), true);
    if ($bytes === false) {
        throw new RuntimeException('Invalid Argon2 string: non-Base64 characters');
    }
    return $bytes;
}

/**
 * Parse a PHC-format Argon2 string (`$argon2id$v=19$m=65536,t=3,p=1$salt$hash`)
 * into its typed parameters. Accepts argon2d / argon2i / argon2id. The digest
 * segment is optional (some encoders omit it); salt and hash are returned as
 * lowercase hex.
 *
 * @throws \RuntimeException on any malformed input.
 */
function parseArgon2(string $encoded): array
{
    if (preg_match('/^\$(argon2(?:d|i|id))\$v=(\d+)\$m=(\d+),t=(\d+),p=(\d+)\$([A-Za-z0-9\/+]+)(?:\$([A-Za-z0-9\/+]+))?$/', trim($encoded), $m) !== 1) {
        throw new RuntimeException('Invalid Argon2 string: expected $argon2id$v=19$m=…,t=…,p=…$salt$hash');
    }
    return [
        'type' => $m[1], 'version' => (int) $m[2], 'memory' => (int) $m[3],
        'iterations' => (int) $m[4], 'parallelism' => (int) $m[5],
        'salt' => bin2hex(phcBase64ToBytes($m[6])),
        'hash' => isset($m[7]) ? bin2hex(phcBase64ToBytes($m[7])) : '',
    ];
}

/**
 * Hash a password with Argon2id (the Password Hashing Competition winner and
 * the recommended mode for password storage). Returns the digest (lowercase
 * hex), the salt used (lowercase hex), and the self-contained PHC string —
 * store that, verify against it.
 *
 * @throws \RuntimeException on bad parameters, an explicit salt / custom digest length, or a PHP build without Argon2.
 */
function argon2Hash(string $password, array $options = []): array
{
    if (!defined('PASSWORD_ARGON2ID')) {
        throw new RuntimeException('This PHP build has no Argon2 support (compile with libargon2)');
    }
    $o = array_merge(ARGON2_DEFAULTS, $options);
    if (isset($options['salt']) || $o['hashLength'] !== ARGON2_DEFAULTS['hashLength']) {
        throw new RuntimeException("PHP's password_hash generates its own 16-byte salt and fixes the digest at 32 bytes");
    }
    foreach ([['memory', 1024, 'Memory must be at least 1024 KiB'], ['iterations', 1, 'Iterations must be at least 1'], ['parallelism', 1, 'Parallelism must be at least 1']] as [$key, $min, $message]) {
        if (!is_int($o[$key]) || $o[$key] < $min) {
            throw new RuntimeException($message);
        }
    }
    $encoded = password_hash($password, PASSWORD_ARGON2ID, [
        'memory_cost' => $o['memory'], 'time_cost' => $o['iterations'], 'threads' => $o['parallelism'],
    ]);
    if (!is_string($encoded)) {
        throw new RuntimeException('argon2 failed: password_hash returned no string');
    }
    // Read salt + digest back out so hash/encoded/salt describe one self-consistent hash.
    $params = parseArgon2($encoded);
    return ['hash' => $params['hash'], 'encoded' => $encoded, 'salt' => $params['salt']];
}

/**
 * Verify a password against a PHC-format encoded hash (as produced by
 * argon2Hash). Returns true on match, false on mismatch; throws only on a
 * malformed encoded string. Any Argon2 type (d/i/id) is accepted - the type
 * is read from the string itself.
 *
 * @throws \RuntimeException on a malformed string or a PHP build without Argon2.
 */
function argon2Verify(string $encoded, string $password): bool
{
    if (!defined('PASSWORD_ARGON2ID')) {
        throw new RuntimeException('This PHP build has no Argon2 support (compile with libargon2)');
    }
    parseArgon2($encoded); // validate format up front
    return password_verify($password, $encoded);
}

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 →