Skip to content

Password Breach Checker — Python 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 Python implementation — the same logic the interactive tool runs, in a shareable, citable form.

"""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: Python 3 (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. hashlib.sha1 stands in for
the canonical lib's WebCrypto crypto.subtle call. The HTTP fetch half of
checkBreach() is transport and stays out (as in every sibling port): callers
fetch range_url_for(prefix) and hand the status + body to check_range().

display source — part of CosmoDev's polyglot tool pages.
"""

from __future__ import annotations

import hashlib
import re
from dataclasses import dataclass

# Free, no key, CORS-enabled. Returns one "SUFFIX:COUNT" line per hash
# sharing the requested prefix (~800 candidates).
HIBP_RANGE_URL = "https://api.pwnedpasswords.com/range/"


@dataclass
class BreachResult:
    """Lookup outcome, mirroring the BreachResult interface in the TS lib.

    ``count`` is 0 when the password was never seen and -1 when the lookup
    failed; ``error`` and ``candidates`` stay None until a lookup ran.
    """

    breached: bool
    count: int
    hash_prefix: str
    hash_suffix: str
    error: str | None = None
    candidates: int | None = None


def sha1_hex(text: str) -> str:
    """SHA-1 of a UTF-8 string as uppercase hex (the format HIBP expects).

    hashlib stands in for the canonical lib's WebCrypto digest; the explicit
    UTF-8 encode plays the role of TextEncoder.
    """
    return hashlib.sha1(text.encode("utf-8")).hexdigest().upper()


def split_hash(hash_hex: str) -> tuple[str, str]:
    """Split a 40-char hash into the 5-char k-anonymity prefix and the
    35-char suffix. Uppercases first, so lowercase hashes are normalized.
    """
    h = str(hash_hex).upper()
    return h[:5], h[5:]


# Mirrors Number.parseInt(s, 10): leading optionally-signed ASCII digits,
# trailing junk ignored, no match when there are no digits at all. HIBP
# counts are plain digits in practice, so fidelity beyond this is unnecessary.
_INT10 = re.compile(r"[+-]?\d+", re.ASCII)


def _parse_int10(s: str) -> int | None:
    """Return the leading integer of ``s`` (already trimmed), or None."""
    m = _INT10.match(s)
    return int(m.group()) if m else None


def parse_range_body(body: str, suffix: str) -> int:
    """Search an HIBP range response for a hash suffix; return its count.

    Never raises; returns 0 when the suffix is not present. Tolerates LF and
    CRLF line endings, blank lines, and leading/trailing whitespace per line.
    """
    if not suffix:
        return 0
    for line in re.split(r"\r?\n", body):
        candidate, sep, value = line.partition(":")
        if not sep or candidate.strip() != suffix:
            continue
        count = _parse_int10(value.strip())
        return count if count is not None and count >= 0 else 0
    return 0


def count_candidates(body: str) -> int:
    """Count the "SUFFIX:COUNT" candidate lines in a range response. Lines
    without a colon, or with an empty suffix field, don't count.
    """
    n = 0
    for line in re.split(r"\r?\n", body):
        candidate, sep, _ = line.partition(":")
        if sep and candidate.strip() != "":
            n += 1
    return n


def range_url_for(prefix: str) -> str:
    """Build the range request URL for a hash prefix — only the 5-char
    prefix ever appears in it (the k-anonymity invariant).
    """
    return HIBP_RANGE_URL + prefix


def check_range(password: str, status: int, body: str) -> BreachResult:
    """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, with candidates counted.
    """
    prefix, suffix = split_hash(sha1_hex(password))
    if not 200 <= status <= 299:
        return BreachResult(False, -1, prefix, suffix, error=f"The breach database returned HTTP {status}")
    count = parse_range_body(body, suffix)
    return BreachResult(count > 0, count, prefix, suffix, candidates=count_candidates(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 →