MD5 vs SHA-256: Hash Algorithms Explained
Deep dive into common hash algorithms (MD5, SHA-1, SHA-256): how they work, security comparisons, use cases, and implementation in JavaScript and Node.js.
What is a Hash Algorithm?
A hash algorithm is a mathematical function that converts arbitrary-length input into fixed-length output. The output is called a "hash value," "digest," or "hash."
Core properties:
- Deterministic: The same input always produces the same output
- Fast computation: Can quickly generate hashes regardless of input size
- Irreversible: Cannot derive the original data from the hash
- Collision-resistant: Hard to find two different inputs that produce the same hash
- Avalanche effect: A small change in input causes a dramatic change in output
Common Hash Algorithm Comparison
| Algorithm | Output Length | Security | Speed | Status |
|---|---|---|---|---|
| MD5 | 128 bits (32 chars) | ❌ Insecure | Fast | Broken, not recommended for security |
| SHA-1 | 160 bits (40 chars) | ⚠️ Weak | Medium | Broken in 2017, being phased out |
| SHA-256 | 256 bits (64 chars) | ✅ Secure | Medium | Currently recommended standard |
| SHA-512 | 512 bits (128 chars) | ✅ Very secure | Slower | High-security scenarios |
| SHA-3 | Variable | ✅ Secure | Medium | Latest standard, being adopted |
| bcrypt | Variable | ✅ Designed for passwords | Slow (intentionally) | Recommended for password storage |
MD5 Explained
Basic Information
- Invented: 1991, designed by Ronald Rivest
- Output length: 128 bits (typically represented as 32 hexadecimal characters)
- Block size: 512 bits
Examples
Input: "Hello, World!"
MD5: 65a8e27d8879283831b664bd8b7f0ad4
Input: "hello, world!" (just lowercase first letter)
MD5: fc3ff98e8c6a0d3087d515c0473f8677 → Completely different!
Why is MD5 No Longer Secure?
- Collision attacks: In 2004, Chinese cryptographer Xiaoyun Wang's team successfully found MD5 collisions
- Too fast: Modern hardware can compute billions of MD5 hashes per second, making brute force easy
- Rainbow tables: Large databases of pre-computed MD5 hashes exist
Can MD5 still be used?
Yes, but only for non-security scenarios:
- ✅ File integrity checking (detecting transmission errors)
- ✅ Data deduplication
- ❌ Password storage
- ❌ Digital signatures
- ❌ Security certificates
SHA-256 Explained
Basic Information
- Family: SHA-2 (Secure Hash Algorithm 2)
- Released: 2001, published by NIST
- Output length: 256 bits (64 hexadecimal characters)
- Block size: 512 bits
- Rounds: 64
Examples
Input: "Hello, World!"
SHA-256: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
Why is SHA-256 More Secure?
- Longer output: 256 bits vs MD5's 128 bits, collision probability is extremely low
- More complex operations: 64 rounds of iteration, each containing various bitwise operations
- Not yet broken: No known practical collision attacks
Application scenarios:
- ✅ Password storage (with salt and iterations)
- ✅ Digital signatures
- ✅ SSL/TLS certificates
- ✅ Blockchain (Bitcoin uses double SHA-256)
- ✅ File integrity verification
Using Hashes in JavaScript
Browser (Web Crypto API)
// SHA-256 hash
async function hashSHA256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
hashSHA256("Hello, World!").then(console.log);
// "dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f"
Note: The browser's native Web Crypto API doesn't support MD5 (because it's insecure).
Node.js
const crypto = require('crypto');
// MD5
function md5(text) {
return crypto.createHash('md5').update(text).digest('hex');
}
// SHA-256
function sha256(text) {
return crypto.createHash('sha256').update(text).digest('hex');
}
// SHA-512
function sha512(text) {
return crypto.createHash('sha512').update(text).digest('hex');
}
console.log(md5("Hello")); // "8b1a9953c4611296a827abf8c47804d7"
console.log(sha256("Hello")); // "185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969"
console.log(sha512("Hello")); // "3615f80c9d293ed7402687f94b22d58e529b8cc7916f8fac7fddf7fbd5af4cf7..."
File Hashing
const crypto = require('crypto');
const fs = require('fs');
function hashFile(filePath, algorithm = 'sha256') {
return new Promise((resolve, reject) => {
const hash = crypto.createHash(algorithm);
const stream = fs.createReadStream(filePath);
stream.on('data', data => hash.update(data));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}
hashFile('./document.pdf').then(console.log);
// "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
Password Storage Best Practices
❌ Wrong Approach
// Don't do this!
const hashedPassword = md5(password);
// or
const hashedPassword = sha256(password);
Why?
- MD5/SHA-256 are designed for fast computation
- Attackers can try billions of passwords per second
- Without salt, the same password produces the same hash
✅ Correct Approach: Use bcrypt
const bcrypt = require('bcrypt');
const SALT_ROUNDS = 12;
// Registration: Hash the password
async function hashPassword(password) {
const salt = await bcrypt.genSalt(SALT_ROUNDS);
return bcrypt.hash(password, salt);
}
// Login: Verify the password
async function verifyPassword(password, hash) {
return bcrypt.compare(password, hash);
}
// Usage
const hashed = await hashPassword("myPassword123");
console.log(hashed);
// "$2b$12$LJ3m4ys3Lg2TBQeD4W8wZ.KB5q9V7ZxH8YR3cF5gH2jK6mN0pD4S"
const isValid = await verifyPassword("myPassword123", hashed);
console.log(isValid); // true
Advantages of bcrypt:
- Intentionally slow: Computation cost is adjustable (salt rounds)
- Built-in salt: Automatically generates random salt for each hash
- GPU attack resistant: Memory-intensive computation limits GPU acceleration
Alternative: argon2
const argon2 = require('argon2');
async function hashPassword(password) {
return argon2.hash(password, {
type: argon2.argon2id,
memoryCost: 2 ** 16,
timeCost: 3,
parallelism: 1
});
}
Argon2 won the Password Hashing Competition in 2015 and is more modern than bcrypt.
Hash vs Encryption
Many people confuse hashing and encryption—they are completely different concepts:
| Feature | Hash | Encryption |
|---|---|---|
| Direction | One-way | Two-way |
| Reversibility | Irreversible | Can be decrypted |
| Output length | Fixed | Variable |
| Key required | No | Yes |
| Purpose | Verify integrity, store passwords | Protect data confidentiality |
| Example algorithms | MD5, SHA-256, bcrypt | AES, RSA, ChaCha20 |
Simple analogy:
- Hash = Meat grinder (meat goes in, ground meat comes out, can't reverse)
- Encryption = Safe (put things in, can take them out with the key)
Common Application Scenarios
1. File Integrity Verification
# Verify MD5 after downloading
md5sum ubuntu-22.04.iso
# e8b3c7d9f0a1e2d3c4b5a69788f9e0d1 ubuntu-22.04.iso
# Compare with official hash value
2. Data Deduplication
// Use hash as unique identifier for content
const contentHash = sha256(fileContent);
if (database.has(contentHash)) {
console.log("File already exists, skipping upload");
}
3. Digital Signatures
1. Sender computes SHA-256 hash of message
2. Encrypts hash with private key (signature)
3. Receiver decrypts signature with public key to get hash
4. Receiver computes message hash themselves and compares
4. Git Version Control
# Git uses SHA-1 hashes to identify each commit
git log --oneline
# a1b2c3d commit message
# ↑ These are the first 7 characters of the commit hash
5. Blockchain
Block header = SHA256(SHA256(previous block hash + transaction data + timestamp + nonce))
Frequently Asked Questions
Can Two Different Inputs Produce the Same Hash?
Theoretically yes (because input space is infinite, output space is finite), but this is called a "collision."
- MD5: Collisions have been demonstrated (insecure)
- SHA-256: No practical collisions discovered yet, probability is about 1/2^128 (virtually impossible)
Can Hash Values Be "Cracked"?
Hashes themselves are irreversible, but attackers can:
- Brute force: Try all possible inputs
- Dictionary attacks: Use lists of common passwords
- Rainbow tables: Pre-computed hash lookup tables
Defense methods:
- Use salt (random salt values)
- Use slow hash algorithms (bcrypt, argon2)
- Increase iteration count
How to Choose a Hash Algorithm?
| Scenario | Recommended Algorithm |
|---|---|
| Password storage | bcrypt or argon2 |
| File verification | SHA-256 |
| Digital signatures | SHA-256 or SHA-3 |
| Data deduplication | SHA-256 or xxHash |
| Legacy system compatibility | MD5 (non-security scenarios only) |
Use the DevKit Hash Generator
DevKit provides an online hash generation tool supporting:
- MD5, SHA-1, SHA-256, SHA-512
- Text and file hash computation
- Real-time calculation results
- Batch hash generation