Skip to content

Password Breach Checker — Rust 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 Rust 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: Rust (std only — no external crates).
//! 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. std has
//! neither a SHA-1 hasher nor an HTTP client, so this port hand-rolls SHA-1
//! (as the `base64` rust snippet hand-rolls Base64) and leaves the fetch half
//! of checkBreach() out: callers fetch range_url_for(prefix) and hand status + body to check_range().
//!
//! display source — part of CosmoDev's polyglot tool pages.

/// Free, no key. Returns one "SUFFIX:COUNT" line per hash sharing the
/// requested prefix (~800 candidates); the suffix match is local.
pub const HIBP_RANGE_URL: &str = "https://api.pwnedpasswords.com/range/";

/// Lookup outcome, mirroring the BreachResult interface in the TS lib.
/// `count` is 0 when never seen and -1 when the lookup failed.
pub struct BreachResult {
    pub breached: bool,
    pub count: i64,
    /// First 5 chars of the uppercase SHA-1 hex — the only part sent to the API.
    pub hash_prefix: String,
    /// Remaining 35 chars, matched locally against the response.
    pub hash_suffix: String,
    /// Set when the lookup failed (e.g. non-2xx status).
    pub error: Option<String>,
    /// Candidate "SUFFIX:COUNT" lines the API returned (all checked locally).
    pub candidates: Option<usize>,
}

/// SHA-1 of raw bytes (FIPS 180-4) — the hand-rolled stand-in for the
/// canonical lib's WebCrypto digest call, since std ships no hasher.
fn sha1(data: &[u8]) -> [u8; 20] {
    let mut h = [0x67452301u32, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
    // Pad: 0x80, zeros to 56 mod 64, then the 64-bit big-endian bit length.
    let mut msg = data.to_vec();
    msg.push(0x80);
    while msg.len() % 64 != 56 {
        msg.push(0);
    }
    msg.extend_from_slice(&((data.len() as u64) * 8).to_be_bytes());
    for chunk in msg.chunks(64) {
        let mut w = [0u32; 80];
        for i in 0..16 {
            w[i] = u32::from_be_bytes(chunk[4 * i..4 * i + 4].try_into().unwrap());
        }
        for i in 16..80 {
            w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
        }
        let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
        for (i, &wi) in w.iter().enumerate() {
            let (f, k) = match i {
                0..=19 => ((b & c) | (!b & d), 0x5A827999u32),
                20..=39 => (b ^ c ^ d, 0x6ED9EBA1),
                40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1BBCDC),
                _ => (b ^ c ^ d, 0xCA62C1D6),
            };
            let t = a.rotate_left(5).wrapping_add(f).wrapping_add(e).wrapping_add(k).wrapping_add(wi);
            (e, d, c, b, a) = (d, c, b.rotate_left(30), a, t);
        }
        for (hi, round) in h.iter_mut().zip([a, b, c, d, e]) {
            *hi = hi.wrapping_add(round);
        }
    }
    let mut out = [0u8; 20];
    for (i, word) in h.iter().enumerate() {
        out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes());
    }
    out
}

/// SHA-1 of a UTF-8 string as uppercase hex (the format HIBP expects).
pub fn sha1_hex(input: &str) -> String {
    sha1(input.as_bytes()).iter().map(|b| format!("{:02X}", b)).collect()
}

/// Split a 40-char hash into the 5-char k-anonymity prefix and the 35-char
/// suffix. Uppercases first, so lowercase hashes are normalized.
pub fn split_hash(hash: &str) -> (String, String) {
    let h = hash.to_uppercase();
    (h.chars().take(5).collect(), h.chars().skip(5).collect())
}

/// Mirror Number.parseInt(s, 10): leading optionally-signed decimal digits,
/// trailing junk ignored; None when there are no digits at all.
fn parse_int10(s: &str) -> Option<i64> {
    let t = s.trim_start();
    let (neg, digits) = match t.strip_prefix('-') {
        Some(rest) => (true, rest),
        None => (false, t.strip_prefix('+').unwrap_or(t)),
    };
    let end = digits.bytes().take_while(|b| b.is_ascii_digit()).count();
    if end == 0 {
        return None;
    }
    let n = digits[..end]
        .bytes()
        .fold(0i64, |acc, b| acc.wrapping_mul(10).wrapping_add(i64::from(b - b'0')));
    Some(if neg { -n } else { n })
}

/// Search an HIBP range response for a hash suffix and return its breach
/// count. Never fails; returns 0 when absent. Tolerates LF and CRLF endings,
/// blank lines, and leading/trailing whitespace per line.
pub fn parse_range_body(body: &str, suffix: &str) -> i64 {
    if suffix.is_empty() {
        return 0;
    }
    for line in body.split('\n') {
        let (candidate, rest) = match line.split_once(':') {
            Some(parts) => parts,
            None => continue,
        };
        if candidate.trim() == suffix {
            return match parse_int10(rest.trim()) {
                Some(n) if n >= 0 => n,
                _ => 0,
            };
        }
    }
    0
}

/// Count the "SUFFIX:COUNT" candidate lines in a range response. Lines
/// without a colon, or with an empty suffix field, don't count.
pub fn count_candidates(body: &str) -> usize {
    body.split('\n')
        .filter(|line| {
            line.split_once(':').map_or(false, |(c, _)| !c.trim().is_empty())
        })
        .count()
}

/// Build the range request URL for a hash prefix — only the 5-char prefix
/// ever appears in it (the k-anonymity invariant).
pub fn range_url_for(prefix: &str) -> String {
    format!("{}{}", 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.
pub fn check_range(password: &str, status: u16, body: &str) -> BreachResult {
    let (hash_prefix, hash_suffix) = split_hash(&sha1_hex(password));
    if !(200..300).contains(&status) {
        return BreachResult {
            breached: false,
            count: -1,
            hash_prefix,
            hash_suffix,
            error: Some(format!("The breach database returned HTTP {}", status)),
            candidates: None,
        };
    }
    let count = parse_range_body(body, &hash_suffix);
    BreachResult {
        breached: count > 0,
        count,
        hash_prefix,
        hash_suffix,
        error: None,
        candidates: Some(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 →