Checksum Verifier — Python 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 Python 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: Python 3.9+ (standard library only).
CosmoDev polyglot showcase port of the `checksum-verifier` tool, ported from
src/lib/checksum-verifier.ts (the canonical TypeScript implementation).
The TS reference hand-rolls MD5 (RFC 1321) because the Web Crypto API does
not ship it; ``hashlib`` has it natively, so this port uses the platform
digests for all four algorithms and ports the verification helpers
(length-based detection, normalization, comparison) as-is.
display source — part of CosmoDev's polyglot tool pages.
"""
from __future__ import annotations
import hashlib
import re
from typing import Literal, NamedTuple, Optional
HashAlgorithm = Literal["md5", "sha1", "sha256", "sha512"]
# Detect the algorithm from the hex length: 32=MD5, 40=SHA-1, 64=SHA-256,
# 128=SHA-512.
LENGTH_TO_ALGO: dict[int, HashAlgorithm] = {
32: "md5",
40: "sha1",
64: "sha256",
128: "sha512",
}
# The Web Crypto algorithm names the TS lib passes to subtle.digest, mapped to
# their hashlib factories.
_SHA_BY_NAME = {
"SHA-1": hashlib.sha1,
"SHA-256": hashlib.sha256,
"SHA-512": hashlib.sha512,
}
class ChecksumResult(NamedTuple):
"""The four checksums of one buffer, as lowercase hex."""
md5: str
sha1: str
sha256: str
sha512: str
class Verification(NamedTuple):
"""The verdict of comparing an expected hash against a computed result."""
algorithm: HashAlgorithm
match: bool
def create_md5() -> "hashlib._Hash":
"""Create an incremental MD5 hasher (RFC 1321).
The returned object responds to ``.update(data)`` — call repeatedly for
chunked input, no length limit — and ``.hexdigest()`` (pad, append the
64-bit length, lowercase hex). MD5 is only for integrity checks - not
security, hence ``usedforsecurity=False``.
"""
return hashlib.md5(usedforsecurity=False)
def md5(data: bytes) -> str:
"""One-shot MD5 of a byte string, as lowercase hex (integrity checks only)."""
return hashlib.md5(data, usedforsecurity=False).hexdigest()
def sha_hex(algorithm: str, data: bytes) -> str:
"""Digest a buffer with SHA-1 / SHA-256 / SHA-512 and return lowercase hex."""
try:
factory = _SHA_BY_NAME[algorithm]
except KeyError:
raise ValueError(f"Unsupported algorithm: {algorithm}") from None
return factory(data).hexdigest()
def compute_checksums(data: bytes) -> ChecksumResult:
"""Compute all four checksums of a buffer."""
return ChecksumResult(
md5=md5(data),
sha1=sha_hex("SHA-1", data),
sha256=sha_hex("SHA-256", data),
sha512=sha_hex("SHA-512", data),
)
# --- Verification helpers -----------------------------------------------------
def normalize_hash(hash: str) -> str:
"""Normalize a pasted hash: drop whitespace and ``:`` grouping, lowercase."""
return re.sub(r"[\s:]", "", hash.strip()).lower()
def detect_hash_algorithm(hash: str) -> Optional[HashAlgorithm]:
"""Detect the algorithm from the hex length.
Returns ``None`` when the string is not a recognizable hex hash of a
supported length.
"""
h = normalize_hash(hash)
if re.fullmatch(r"[0-9a-f]+", h) is None:
return None
return LENGTH_TO_ALGO.get(len(h))
def verify_checksum(expected: str, result: ChecksumResult) -> Optional[Verification]:
"""Compare an expected hash against a computed result.
Returns ``None`` when the expected string is not a recognizable hex hash
of a supported length.
"""
algorithm = detect_hash_algorithm(expected)
if algorithm is None:
return None
return Verification(algorithm, normalize_hash(expected) == getattr(result, 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 →