Hash Functions Explained: MD5, SHA-1, SHA-256 and Checksums
A hash function takes input of any size (a word, a file, a whole disk image) and returns a short, fixed-size value called a digest or hash. The same input always gives the same digest, and changing a single bit of the input gives a completely different one. That makes a digest a fingerprint: compare two fingerprints and you know whether the data is identical, without comparing the data itself.
Examples use Python 3.11 or later (for hashlib.file_digest) and the standard command line tools on Linux, macOS and Windows. All output shown is real.
What a cryptographic hash guarantees
Hash tables, caches and CRC32 checks use fast, non-cryptographic hashes that only need to spread values evenly. A cryptographic hash must also resist deliberate attack:
- Preimage resistance (one-way): given a digest, you cannot find an input that produces it, except by guessing inputs.
- Second-preimage resistance: given one input, you cannot find a different input with the same digest.
- Collision resistance: you cannot find any two different inputs with the same digest.
Collisions must exist (there are infinitely many inputs and a fixed number of digests), but for a sound algorithm, finding one should be computationally out of reach.
The common algorithms
| Algorithm | Digest size | Hex characters | Status |
|---|---|---|---|
| MD5 | 128 bits | 32 | Broken: collisions can be produced cheaply (demonstrated since 2004) |
| SHA-1 | 160 bits | 40 | Broken for collision resistance (a practical collision was published in 2017) |
| SHA-256 | 256 bits | 64 | Secure; the usual choice |
| SHA-384, SHA-512 | 384, 512 bits | 96, 128 | Secure |
| SHA-3, BLAKE2 | various | various | Secure; also in Python's hashlib |
MD5 and SHA-1 are still fine as non-security checksums (spotting accidental corruption, deduplicating your own files) and you will meet them in legacy systems. Do not use them where someone might try to forge a match: integrity checks on downloads, signatures, certificates. Use SHA-256 or stronger.
Hashing text in Python
Hash functions work on bytes, so encode text first, normally as UTF-8. hexdigest() returns the digest as hexadecimal text:
import hashlib
for name in ["md5", "sha1", "sha256", "sha512"]:
digest = hashlib.new(name, b"hello").hexdigest()
print(f"{name:7} {len(digest) * 4:4} bits {digest[:32]}") # first 32 hex chars
# One character changes the whole digest (the avalanche effect)
print(hashlib.sha256("hello".encode("utf-8")).hexdigest())
print(hashlib.sha256("Hello".encode("utf-8")).hexdigest())
md5 128 bits 5d41402abc4b2a76b9719d911017c592
sha1 160 bits aaf4c61ddcc5e8a2dabede0f3b482cd9
sha256 256 bits 2cf24dba5fb0a30e26e83b2ac5b9e29e
sha512 512 bits 9b71d224bd62f3785d96d46ad3ea3d73
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
"hello" and "Hello" differ by one character, yet the two SHA-256 digests share nothing recognizable. This is the avalanche effect. Because the input encoding matters, "café" hashed as UTF-8 and as Latin-1 gives two different digests; always hash the same bytes on both sides. To check a value by hand, the Hash Generator computes MD5, SHA-1, SHA-256, SHA-384 and SHA-512 of text in your browser.
Verifying a downloaded file
Projects often publish a SHA-256 checksum next to each download. After downloading, compute the file's hash and compare. On the command line:
# Linux
sha256sum release.tar.gz
# macOS
shasum -a 256 release.tar.gz
# Check against a .sha256 file in the "hash filename" format
shasum -a 256 -c release.tar.gz.sha256 # Linux: sha256sum -c release.tar.gz.sha256
5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03 release.tar.gz
release.tar.gz: OK
On Windows, PowerShell's Get-FileHash release.tar.gz uses SHA-256 by default, and certutil -hashfile release.tar.gz SHA256 works in the Command Prompt. Get-FileHash prints the digest in uppercase; hex digests are case-insensitive, so compare them ignoring case.
The same check in Python reads the file in binary mode, so line endings and encodings cannot change what is hashed, and file_digest reads it in chunks, so a multi-gigabyte file does not need to fit in memory:
import hashlib
import sys
def sha256_of_file(path):
with open(path, "rb") as f: # binary mode: hash the exact bytes
return hashlib.file_digest(f, "sha256").hexdigest() # Python 3.11+
path, expected = sys.argv[1], sys.argv[2].strip().lower()
actual = sha256_of_file(path)
if actual == expected:
print(f"OK: {path} matches")
else:
print(f"MISMATCH: {path}\n expected {expected}\n actual {actual}")
sys.exit(1)
Save it as check_sha256.py and run it with the file and the published hash:
python check_sha256.py release.tar.gz 5891b5b522d5df086d0ff0b110fbd9d21bb4fc7163af34d08286a2e846f6be03
OK: release.tar.gz matches
What a checksum does not prove
A matching checksum proves that your file is the same as the file the checksum was made from. It does not prove who made it. If an attacker can replace the download, they can usually replace a checksum served from the same place. So:
- Get the expected hash from the project's official site over HTTPS, ideally from a different place than the file itself.
- Where a project signs its releases (GPG signatures, signed packages, signed commits), verify the signature: a signature proves who published the file.
- Between two systems that share a secret, use an HMAC, a hash keyed with that secret. Webhook providers commonly sign each request body this way so the receiver can reject forged requests.
import hashlib
import hmac
import os
secret = os.environ["WEBHOOK_SECRET"].encode() # shared secret, never in code
def sign(body: bytes) -> str:
return hmac.new(secret, body, hashlib.sha256).hexdigest()
def is_authentic(body: bytes, signature: str) -> bool:
# compare_digest takes the same time whether the first or last character differs
return hmac.compare_digest(sign(body), signature)
body = b'{"event": "paid", "order": 1042}'
signature = sign(body) # the sender computes this
print(is_authentic(body, signature)) # True
print(is_authentic(body.replace(b"1042", b"1043"), signature)) # False: body changed
Run it with the secret in an environment variable (for example WEBHOOK_SECRET=$(openssl rand -hex 32) python hmac_check.py); it prints True then False. hmac.compare_digest takes the same time no matter where two values differ, so an attacker cannot learn a valid signature one character at a time from response timings. Use it whenever you compare secrets or signatures.
Hashes are not encryption, and not password storage
- A hash cannot be "decrypted". There is no key and no way back, which is why hashes are used for fingerprints and encryption is used when the data must be read again.
- A fast hash is the wrong tool for passwords. SHA-256 is designed to be fast, so an attacker who steals the database can test huge numbers of guesses per second on ordinary hardware. Passwords need a deliberately slow, salted password-hashing function such as Argon2id; see storing passwords safely in Python. For the same reason, the Hash Generator is for checking data, not for storing passwords.
- Base64 and other encodings are neither hashes nor encryption: they are reversible by anyone (Base64 explained).
Where else you meet hashes
- Git identifies every commit, file and folder by a hash of its contents: SHA-1 by default (in a hardened form that detects known collision attacks), with SHA-256 available for new repositories and planned as a future default. That is why a commit ID such as
3f2a9c1changes if anything in the commit changes. - Caching and deduplication: content-addressed storage names each object by its hash.
- Lock files in package managers record a hash of each dependency so a package whose contents changed is rejected.
Common mistakes
- Hashing a string without fixing the encoding, or hashing a file opened in text mode.
- Comparing a lowercase digest with an uppercase one as plain strings.
- Copying the checksum and the file from the same untrusted mirror.
- Choosing MD5 or SHA-1 for anything an attacker could target.
- Using a plain hash where you need an HMAC (authenticity) or a password hash (stored passwords).
The hashlib documentation lists every algorithm available in Python.