"Should I use MD5 or SHA-256?" is one of those questions where the answer depends entirely on what you're protecting. Use MD5 for the wrong thing and you've got a security vulnerability. Use SHA-256 where MD5 would suffice and you've added unnecessary complexity (though, honestly, the performance difference is rarely a real problem anymore).
This guide cuts through the noise: what each algorithm does, why MD5 is broken for security purposes, where it's still perfectly fine, and a simple decision framework for choosing between them.
How MD5 and SHA-256 Work (Briefly)
Both are cryptographic hash functions—they take input of any size and produce a fixed-length output (the "digest" or "hash"). The same input always produces the same hash. Even a one-bit change in input produces a completely different hash.
MD5 (Message Digest 5):
- Published in 1992 by Ronald Rivest
- Produces a 128-bit (16-byte) hash, displayed as 32 hex characters
- Example:
echo -n "hello" | md5→5d41402abc4b2a76b9719d911017c592
SHA-256 (Secure Hash Algorithm 256-bit):
- Published in 2001 by NIST as part of the SHA-2 family
- Produces a 256-bit (32-byte) hash, displayed as 64 hex characters
- Example:
echo -n "hello" | shasum -a 256→2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Both are one-way functions: you cannot reverse the hash to recover the original input. Both are deterministic: same input, same output, every time.
The critical difference is in their resistance to collision attacks.
Why MD5 Is Broken for Security
A collision occurs when two different inputs produce the same hash. For a hash function to be secure, finding a collision should be computationally infeasible.
MD5 failed this requirement. In 2004, researchers demonstrated practical collision attacks against MD5. By 2008, attackers created a rogue SSL certificate by exploiting MD5 collisions in the certificate signing process. In 2012, the Flame malware used an MD5 collision to forge a Microsoft code-signing certificate.
What this means in practice:
An attacker can craft two different files with the same MD5 hash. If your system trusts an MD5 hash to verify integrity or authenticity, the attacker can substitute a malicious file that produces the same hash as the legitimate one.
# Two different PDFs, same MD5 hash (demonstrated by researchers)
# File A: legitimate document
# File B: malicious document with same MD5
md5(file_a) == md5(file_b) # True — but contents differ
SHA-256 has no known practical collision attacks as of 2026. The theoretical best attack requires approximately 2^128 operations, which is beyond any foreseeable computing capability.
Where MD5 Is Still Acceptable
MD5 isn't universally evil. It's fine when collision resistance doesn't matter—when an attacker has no incentive or ability to craft a collision against your specific use case.
File integrity checksums (non-adversarial):
Verifying that a download completed without corruption (not tampering):
# Checking a download against a published checksum
md5sum ubuntu-26.04-desktop-amd64.iso
# Compare with the hash on the download page
If you're just checking for accidental corruption (bit flips, incomplete transfers), MD5 works. But if you need to verify that a file wasn't intentionally modified by an attacker, use SHA-256.
Cache keys and deduplication:
Using a hash as a fast lookup key where collisions are handled gracefully:
import hashlib
def get_cache_key(content):
# MD5 is fine here — worst case, a collision causes a cache miss
return hashlib.md5(content).hexdigest()
If a collision occurs, you get a cache miss or a redundant copy. No security impact.
Non-security file deduplication:
Backup tools that skip unchanged files:
# rsync-style: skip files whose content hash hasn't changed
find . -type f -exec md5sum {} \; | sort > manifest.md5
Legacy system compatibility:
Some older APIs, package managers, or file formats only support MD5 checksums. In these cases, you're stuck with it—but add SHA-256 verification wherever possible.
Where You Must Use SHA-256 (or Better)
Digital signatures and certificates:
Any system that signs data and verifies the signature must use a collision-resistant hash. SHA-256 is the minimum standard:
# Signing a release artifact
openssl dgst -sha256 -sign private_key.pem -out release.sig release.tar.gz
openssl dgst -sha256 -verify public_key.pem -signature release.sig release.tar.gz
Password storage (but not directly):
Never hash passwords with raw MD5 or raw SHA-256. Both are too fast, making brute-force attacks trivial with modern GPUs. Use a purpose-built password hashing function:
# WRONG — never do this
import hashlib
password_hash = hashlib.sha256(password.encode()).hexdigest()
# RIGHT — use bcrypt, scrypt, or argon2
import bcrypt
password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt(rounds=12))
Argon2id is the current gold standard for password hashing. bcrypt remains widely used and well-vetted. The key property these provide is slowness—they're deliberately expensive to compute, making brute-force attacks impractical.
Blockchain and cryptocurrency:
Bitcoin and most blockchain systems use SHA-256 for block hashing and proof-of-work. The collision resistance is essential to the integrity of the chain.
API request signing and HMAC:
When signing API requests or generating HMAC tokens:
import hmac
import hashlib
# HMAC-SHA256 for API authentication
signature = hmac.new(
secret_key.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
Git and content-addressable storage:
Git migrated from SHA-1 to SHA-256 for object hashing. Any content-addressable system where an attacker might inject crafted content should use SHA-256.
Compliance and regulatory requirements:
PCI-DSS, HIPAA, SOC 2, and most compliance frameworks explicitly prohibit MD5 for cryptographic purposes and require SHA-256 or stronger.
Performance Comparison
The speed difference between MD5 and SHA-256 has narrowed significantly with hardware SHA extensions (Intel SHA-NI, ARM Crypto Extensions):
| Algorithm | Throughput (modern CPU with HW accel) | Output Size | |-----------|--------------------------------------|-------------| | MD5 | ~1.5 GB/s | 128 bits | | SHA-256 | ~1.2 GB/s (with SHA-NI) | 256 bits | | SHA-256 | ~500 MB/s (software only) | 256 bits |
On modern hardware with SHA-NI support (most CPUs since 2017), SHA-256 is fast enough that the performance difference is irrelevant for virtually all applications. You'd need to be hashing tens of gigabytes per second before MD5's speed advantage matters—and at that scale, you have bigger architectural questions to answer.
For typical use cases—hashing API payloads, verifying file downloads, generating cache keys—the difference is microseconds. Choose based on security requirements, not speed.
Decision Framework
Use this flowchart to decide:
1. Is this for security purposes? (authentication, signing, certificates, integrity verification against adversaries)
- Yes → Use SHA-256 minimum. Never MD5.
- No → Continue to question 2.
2. Is this for password storage?
- Yes → Use neither. Use Argon2id or bcrypt.
- No → Continue to question 3.
3. Could an attacker benefit from crafting a collision? (e.g., substituting a malicious file that matches a legitimate hash)
- Yes → Use SHA-256.
- No → MD5 is acceptable (cache keys, non-adversarial checksums, dedup).
4. Are there compliance or regulatory requirements?
- Yes → Follow the standard (almost always SHA-256+).
- No → Use your judgment based on questions 1-3.
When in doubt, use SHA-256. The performance cost is negligible, the output is still compact (64 hex characters), and you never have to worry about whether your "non-security" use case might become security-relevant later.
Generating Hashes Locally
Whether you need an MD5 checksum for a cache key or a SHA-256 hash for file verification, you can generate both without sending your data to a server.
The SHA-256 Hash Generator and MD5 Hash Generator both process input entirely in your browser using the Web Crypto API. Your text, files, or API payloads never leave your machine—which matters when you're hashing sensitive content like API keys, personal data, or proprietary code before sending it to a third party.
For quick command-line hashing:
# SHA-256
echo -n "your input" | shasum -a 256
# MD5
echo -n "your input" | md5
# File hashing
shasum -a 256 important-file.pdf
md5sum important-file.pdf # Linux
The bottom line: MD5 is a fast checksum for non-adversarial scenarios. SHA-256 is the baseline for anything security-related. And for passwords, use neither—reach for Argon2id or bcrypt. When unsure, SHA-256 is the safe default with essentially zero downside.
相关文章
Online RSA Encryption/Decryption: Asymmetric Crypto and Digital Signatures
Learn RSA asymmetric encryption algorithm principles and applications. Understand public/private key encryption, digital signatures, key pair generation, and use in HTTPS and API authentication.
Complete Guide to MD5 Hash: How It Works, Uses, and Security
Deep dive into the MD5 algorithm, its common uses, and security vulnerabilities. Learn the differences between MD5, SHA-1, and SHA-256, and when MD5 is still okay to use.
Is It Safe to Paste Your JWT into an Online Decoder? On Token Leakage Risk
Is it safe to paste a JWT token into an online decoder? This article analyzes the security risks of online JWT decoding, token leakage risk, and how to safely decode a JWT without exposing private data.