Skip to content

Checksum Verifier — Rust source

Drag and drop a file to compute its MD5, SHA-1, SHA-256, and SHA-512 checksums. Paste an expected hash to verify integrity - detect tampered or corrupted downloads instantly. Runs entirely in your browser.

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

//! checksum-verifier — MD5 / SHA-1 / SHA-256 / SHA-512 checksums + verification.
//!
//! Language: Rust (2021 edition, std only — no external crates).
//! CosmoDev polyglot showcase port of the `checksum-verifier` tool, ported from
//! src/lib/checksum-verifier.ts (the canonical TypeScript implementation).
//!
//! Rust's std has no hash algorithms at all, so — like the C and C++ siblings
//! in this directory — all four digests are implemented from their
//! specifications as one-shot functions (the SHA half of the lib's `shaHex`).
//! MD5 / SHA-1 are here for integrity checks against published sums; neither
//! is collision-resistant.

/// Lowercase hex for a byte slice — the shape every digest below returns.
fn to_hex(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        out.push_str(&format!("{byte:02x}"));
    }
    out
}

/// Pad a message for a 64-byte-block Merkle–Damgård hash: the message, 0x80,
/// zeros to 56 mod 64, then the 64-bit bit length (MD5 little-endian,
/// SHA-1 / SHA-256 big-endian).
fn pad64(data: &[u8], little: bool) -> Vec<u8> {
    let bit_len = (data.len() as u64).wrapping_mul(8);
    let padded = (data.len() + 8) / 64 * 64 + 64;
    let mut buf = vec![0u8; padded];
    buf[..data.len()].copy_from_slice(data);
    buf[data.len()] = 0x80;
    let len_bytes = if little { bit_len.to_le_bytes() } else { bit_len.to_be_bytes() };
    buf[padded - 8..].copy_from_slice(&len_bytes);
    buf
}

/// Pad for SHA-512's 128-byte blocks: the length is 128-bit big-endian.
fn pad128(data: &[u8]) -> Vec<u8> {
    let bits = (data.len() as u128).wrapping_mul(8);
    let padded = (data.len() + 16) / 128 * 128 + 128;
    let mut buf = vec![0u8; padded];
    buf[..data.len()].copy_from_slice(data);
    buf[data.len()] = 0x80;
    buf[padded - 16..].copy_from_slice(&bits.to_be_bytes());
    buf
}

/// One-shot MD5 (RFC 1321) as lowercase hex — the TS reference hand-rolls it
/// because Web Crypto does not ship MD5, and Rust std ships no digests either.
pub fn md5(data: &[u8]) -> String {
    // Per-round shift amounts (RFC 1321, section 3.4).
    const S: [u32; 64] = [
        7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
        5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
        4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
        6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
    ];
    // T[i] = floor(2^32 * |sin(i + 1)|) — the RFC 1321 sine table, computed
    // exactly as the TS reference does (IEEE-754 keeps it deterministic).
    let k: [u32; 64] = std::array::from_fn(|i| ((i as f64 + 1.0).sin().abs() * 4294967296.0).floor() as u32);

    let (mut a0, mut b0, mut c0, mut d0): (u32, u32, u32, u32) =
        (0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476);
    for block in pad64(data, true).chunks_exact(64) {
        let mut m = [0u32; 16];
        for (i, word) in m.iter_mut().enumerate() {
            *word = u32::from_le_bytes(block[i * 4..i * 4 + 4].try_into().unwrap());
        }
        let (mut a, mut b, mut c, mut d) = (a0, b0, c0, d0);
        for i in 0..64 {
            let (f, g) = match i {
                0..=15 => ((b & c) | (!b & d), i),
                16..=31 => ((d & b) | (!d & c), (5 * i + 1) % 16),
                32..=47 => (b ^ c ^ d, (3 * i + 5) % 16),
                _ => (c ^ (b | !d), (7 * i) % 16),
            };
            let sum = f.wrapping_add(a).wrapping_add(k[i]).wrapping_add(m[g]);
            let tmp = d;
            d = c;
            c = b;
            b = b.wrapping_add(sum.rotate_left(S[i]));
            a = tmp;
        }
        a0 = a0.wrapping_add(a);
        b0 = b0.wrapping_add(b);
        c0 = c0.wrapping_add(c);
        d0 = d0.wrapping_add(d);
    }
    let mut digest = [0u8; 16];
    for (i, word) in [a0, b0, c0, d0].into_iter().enumerate() {
        digest[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes());
    }
    to_hex(&digest)
}

/// One-shot SHA-1 (FIPS 180-4) as lowercase hex. Integrity checks only.
pub fn sha1(data: &[u8]) -> String {
    let (mut h0, mut h1, mut h2, mut h3, mut h4): (u32, u32, u32, u32, u32) =
        (0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476, 0xc3d2_e1f0);
    for block in pad64(data, false).chunks_exact(64) {
        let mut w = [0u32; 80];
        for (i, word) in w.iter_mut().take(16).enumerate() {
            *word = u32::from_be_bytes(block[i * 4..i * 4 + 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) = (h0, h1, h2, h3, h4);
        for i in 0..80 {
            let (f, k) = match i {
                0..=19 => ((b & c) | (!b & d), 0x5a82_7999u32),
                20..=39 => (b ^ c ^ d, 0x6ed9_eba1),
                40..=59 => ((b & c) | (b & d) | (c & d), 0x8f1b_bcdc),
                _ => (b ^ c ^ d, 0xca62_c1d6),
            };
            let tmp = a
                .rotate_left(5)
                .wrapping_add(f)
                .wrapping_add(k)
                .wrapping_add(e)
                .wrapping_add(w[i]);
            e = d;
            d = c;
            c = b.rotate_left(30);
            b = a;
            a = tmp;
        }
        h0 = h0.wrapping_add(a);
        h1 = h1.wrapping_add(b);
        h2 = h2.wrapping_add(c);
        h3 = h3.wrapping_add(d);
        h4 = h4.wrapping_add(e);
    }
    let mut digest = [0u8; 20];
    for (i, word) in [h0, h1, h2, h3, h4].into_iter().enumerate() {
        digest[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    to_hex(&digest)
}

/// One-shot SHA-256 (FIPS 180-4) as lowercase hex.
pub fn sha256(data: &[u8]) -> String {
    // First 32 bits of the fractional parts of the cube roots (K) and square
    // roots (H0) of the first primes (FIPS 180-4, sections 4.2.2 and 5.3.3).
    const H0: [u32; 8] = [
        0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
        0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
    ];
    const K: [u32; 64] = [
        0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
        0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
        0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
        0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
        0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
        0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
        0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
        0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
    ];
    let mut h = H0;
    for block in pad64(data, false).chunks_exact(64) {
        let mut w = [0u32; 64];
        for (i, word) in w.iter_mut().take(16).enumerate() {
            *word = u32::from_be_bytes(block[i * 4..i * 4 + 4].try_into().unwrap());
        }
        for i in 16..64 {
            let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
            let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
            w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
        }
        let mut v = h;
        for (i, &ki) in K.iter().enumerate() {
            let s1 = v[4].rotate_right(6) ^ v[4].rotate_right(11) ^ v[4].rotate_right(25);
            let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
            let t1 = v[7].wrapping_add(s1).wrapping_add(ch).wrapping_add(ki).wrapping_add(w[i]);
            let s0 = v[0].rotate_right(2) ^ v[0].rotate_right(13) ^ v[0].rotate_right(22);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v = [t1.wrapping_add(t2), v[0], v[1], v[2], v[3].wrapping_add(t1), v[4], v[5], v[6]];
        }
        for (hi, vi) in h.iter_mut().zip(v) {
            *hi = hi.wrapping_add(vi);
        }
    }
    let mut digest = [0u8; 32];
    for (i, word) in h.into_iter().enumerate() {
        digest[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
    }
    to_hex(&digest)
}

/// One-shot SHA-512 (FIPS 180-4) as lowercase hex — SHA-256's 64-bit twin:
/// 80 rounds over 128-byte blocks with u64 words.
pub fn sha512(data: &[u8]) -> String {
    // First 64 bits of the fractional parts of the cube roots (K) and square
    // roots (H0) of the first primes (FIPS 180-4, sections 4.2.3 and 5.3.4).
    const H0: [u64; 8] = [
        0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
        0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
    ];
    const K: [u64; 80] = [
        0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
        0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
        0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
        0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694,
        0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
        0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
        0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4,
        0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70,
        0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
        0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
        0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30,
        0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8,
        0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
        0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
        0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
        0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b,
        0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
        0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b,
        0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
        0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817,
    ];
    let mut h = H0;
    for block in pad128(data).chunks_exact(128) {
        let mut w = [0u64; 80];
        for (i, word) in w.iter_mut().take(16).enumerate() {
            *word = u64::from_be_bytes(block[i * 8..i * 8 + 8].try_into().unwrap());
        }
        for i in 16..80 {
            let s0 = w[i - 15].rotate_right(1) ^ w[i - 15].rotate_right(8) ^ (w[i - 15] >> 7);
            let s1 = w[i - 2].rotate_right(19) ^ w[i - 2].rotate_right(61) ^ (w[i - 2] >> 6);
            w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
        }
        let mut v = h;
        for (i, &ki) in K.iter().enumerate() {
            let s1 = v[4].rotate_right(14) ^ v[4].rotate_right(18) ^ v[4].rotate_right(41);
            let ch = (v[4] & v[5]) ^ (!v[4] & v[6]);
            let t1 = v[7].wrapping_add(s1).wrapping_add(ch).wrapping_add(ki).wrapping_add(w[i]);
            let s0 = v[0].rotate_right(28) ^ v[0].rotate_right(34) ^ v[0].rotate_right(39);
            let maj = (v[0] & v[1]) ^ (v[0] & v[2]) ^ (v[1] & v[2]);
            let t2 = s0.wrapping_add(maj);
            v = [t1.wrapping_add(t2), v[0], v[1], v[2], v[3].wrapping_add(t1), v[4], v[5], v[6]];
        }
        for (hi, vi) in h.iter_mut().zip(v) {
            *hi = hi.wrapping_add(vi);
        }
    }
    let mut digest = [0u8; 64];
    for (i, word) in h.into_iter().enumerate() {
        digest[i * 8..i * 8 + 8].copy_from_slice(&word.to_be_bytes());
    }
    to_hex(&digest)
}

// --- Public API (the lib's exports) -------------------------------------------

/// Digest a buffer with "SHA-1" / "SHA-256" / "SHA-512" and return lowercase hex.
pub fn sha_hex(algorithm: &str, data: &[u8]) -> Result<String, String> {
    match algorithm {
        "SHA-1" => Ok(sha1(data)),
        "SHA-256" => Ok(sha256(data)),
        "SHA-512" => Ok(sha512(data)),
        other => Err(format!("Unsupported algorithm: {other}")),
    }
}

/// The four checksums of one buffer, as lowercase hex.
pub struct ChecksumResult {
    pub md5: String,
    pub sha1: String,
    pub sha256: String,
    pub sha512: String,
}

impl ChecksumResult {
    /// The lowercase-hex digest for an algorithm name ("md5" … "sha512").
    fn get(&self, algorithm: &str) -> &str {
        match algorithm {
            "md5" => &self.md5,
            "sha1" => &self.sha1,
            "sha256" => &self.sha256,
            _ => &self.sha512,
        }
    }
}

/// Compute all four checksums of a buffer.
pub fn compute_checksums(data: &[u8]) -> ChecksumResult {
    ChecksumResult {
        md5: md5(data),
        sha1: sha1(data),
        sha256: sha256(data),
        sha512: sha512(data),
    }
}

/// Normalize a pasted hash: drop whitespace and `:` grouping, lowercase.
fn normalize_hash(hash: &str) -> String {
    hash.trim()
        .chars()
        .filter(|c| !c.is_whitespace() && *c != ':')
        .flat_map(char::to_lowercase)
        .collect()
}

/// Detect the algorithm from the hex length: 32=MD5, 40=SHA-1, 64=SHA-256,
/// 128=SHA-512. `None` for non-hex input or an unrecognized length.
pub fn detect_hash_algorithm(hash: &str) -> Option<&'static str> {
    let h = normalize_hash(hash);
    if h.is_empty() || !h.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
        return None;
    }
    match h.len() {
        32 => Some("md5"),
        40 => Some("sha1"),
        64 => Some("sha256"),
        128 => Some("sha512"),
        _ => None,
    }
}

/// The verdict of comparing an expected hash against a computed result.
pub struct Verification {
    pub algorithm: &'static str,
    /// `match` is a Rust keyword — kept as a raw identifier to mirror the lib.
    pub r#match: bool,
}

/// Compare an expected hash against a computed result. Returns `None` when the
/// expected string is not a recognizable hex hash of a supported length.
pub fn verify_checksum(expected: &str, result: &ChecksumResult) -> Option<Verification> {
    let algorithm = detect_hash_algorithm(expected)?;
    Some(Verification { algorithm, r#match: normalize_hash(expected) == result.get(algorithm) })
}

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 →