Skip to content

Password Breach Checker — PHP source

Check if a password has appeared in known data breaches using k-anonymity. Only the first 5 characters of the SHA-1 hash are sent - your full password never leaves your browser.

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

<?php
/**
 * breach-checker — password breach lookup via Have I Been Pwned's Pwned
 * Passwords API, using k-anonymity: only the first 5 characters of the SHA-1
 * hash ever leave the machine.
 *
 * Language: PHP 7.4+ (standard library only).
 * CosmoDev polyglot showcase port of the `breach-checker` tool, ported from
 * src/lib/breach-checker.ts.
 *
 * Why this file exists: it isolates the pure core of the k-anonymity protocol
 * — hash locally, send only the 5-char prefix, match the suffix locally — so
 * the service never learns which password was checked. hash('sha1') stands in
 * for the canonical lib's WebCrypto call: PHP strings are byte buffers, so it
 * already digests the UTF-8 byte sequence. The HTTP fetch half of
 * checkBreach() is transport and stays out (as in every sibling port):
 * callers fetch the rangeUrlFor(prefix) URL and hand status + body to
 * checkRange().
 *
 * display source — part of CosmoDev's polyglot tool pages.
 */

declare(strict_types=1);

final class BreachChecker
{
    /** Free, no key, CORS-enabled. Returns one "SUFFIX:COUNT" line per hash
     * sharing the requested prefix (~800 candidates). */
    public const HIBP_RANGE_URL = 'https://api.pwnedpasswords.com/range/';

    /** SHA-1 of a UTF-8 string as uppercase hex (the format HIBP expects). */
    public static function sha1Hex(string $input): string
    {
        return strtoupper(hash('sha1', $input));
    }

    /**
     * Split a 40-char hash into the 5-char k-anonymity prefix and the
     * 35-char suffix. Uppercases first, so lowercase hashes are normalized.
     *
     * @return array{prefix: string, suffix: string}
     */
    public static function splitHash(string $hash): array
    {
        $h = strtoupper($hash);
        return ['prefix' => substr($h, 0, 5), 'suffix' => substr($h, 5)];
    }

    /**
     * Mirror Number.parseInt(s, 10): leading optionally-signed digits,
     * trailing junk ignored, null when there are no digits at all. HIBP
     * counts are plain digits, so fidelity beyond this is unnecessary.
     */
    private static function parseInt10(string $s): ?int
    {
        return preg_match('/^[+-]?\d+/', $s, $m) === 1 ? (int) $m[0] : null;
    }

    /**
     * Search an HIBP range response for a hash suffix and return its breach
     * count. Never throws; returns 0 when the suffix is not present.
     * Tolerates LF and CRLF line endings, blank lines, and per-line
     * whitespace.
     */
    public static function parseRangeBody(string $body, string $suffix): int
    {
        if ($suffix === '') {
            return 0;
        }
        foreach (preg_split('/\r?\n/', $body) as $line) {
            $idx = strpos($line, ':');
            if ($idx === false || trim(substr($line, 0, $idx)) !== $suffix) {
                continue;
            }
            $count = self::parseInt10(trim(substr($line, $idx + 1)));
            return $count !== null && $count >= 0 ? $count : 0;
        }
        return 0;
    }

    /**
     * Count the "SUFFIX:COUNT" candidate lines in a range response. Lines
     * without a colon, or with an empty suffix field, don't count.
     */
    public static function countCandidates(string $body): int
    {
        $n = 0;
        foreach (preg_split('/\r?\n/', $body) as $line) {
            $idx = strpos($line, ':');
            if ($idx !== false && trim(substr($line, 0, $idx)) !== '') {
                $n++;
            }
        }
        return $n;
    }

    /**
     * Build the range request URL for a prefix — only the 5-char prefix ever
     * appears in it (the k-anonymity invariant).
     */
    public static function rangeUrlFor(string $prefix): string
    {
        return self::HIBP_RANGE_URL . $prefix;
    }

    /**
     * The pure half of checkBreach(): classify an already-fetched range
     * response for a password. A non-2xx status mirrors the lib's
     * !response.ok branch — count -1 with an HTTP error message; otherwise
     * the suffix is matched locally and the breach count interpreted.
     * Mirrors the BreachResult interface in the TypeScript lib: count is
     * 0 = never seen, -1 = lookup failed.
     *
     * @return array{breached: bool, count: int, hashPrefix: string, hashSuffix: string, error: string|null, candidates: int|null}
     */
    public static function checkRange(string $password, int $status, string $body): array
    {
        ['prefix' => $prefix, 'suffix' => $suffix] = self::splitHash(self::sha1Hex($password));
        if ($status < 200 || $status > 299) {
            return ['breached' => false, 'count' => -1, 'hashPrefix' => $prefix,
                'hashSuffix' => $suffix, 'error' => "The breach database returned HTTP {$status}",
                'candidates' => null];
        }
        $count = self::parseRangeBody($body, $suffix);
        return ['breached' => $count > 0, 'count' => $count, 'hashPrefix' => $prefix,
            'hashSuffix' => $suffix, 'error' => null, 'candidates' => self::countCandidates($body)];
    }
}

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 →