Hash Generator Guide: MD5, SHA-1, SHA-256, and Beyond
Cryptographic hashes are fundamental to security. Learn the differences between MD5, SHA-1, SHA-256, and when to use each algorithm.
What is a Hash Function?
A cryptographic hash function takes input data of any size and produces a fixed-size output (the hash or digest). Good hash functions have these properties:
- Deterministic: Same input always produces same output
- Fast: Quick to compute for any input
- One-way: Cannot reverse the hash to find input
- Collision-resistant: Hard to find two inputs with same hash
- Avalanche effect: Small input change = completely different hash
Hash Examples
Input: "Hello"
MD5: 8b1a9953c4611296a827abf8c47804d7
SHA-1: f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0
SHA-256: 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969
Input: "Hello!" (added one character)
SHA-256: 334d016f755cd6dc58c53a86e183882f8ec14f52fb05345887c8a5edd42c87b7
(Completely different!)Common Hash Algorithms
MD5 (Message Digest 5)
- Output: 128 bits (32 hex characters)
- Status: Broken for security purposes
- Still OK for: Checksums, non-security uses
MD5("Hello") = 8b1a9953c4611296a827abf8c47804d7SHA-1 (Secure Hash Algorithm 1)
- Output: 160 bits (40 hex characters)
- Status: Deprecated, collisions found
- Still used: Legacy systems, Git (but transitioning)
SHA-1("Hello") = f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0SHA-256 (SHA-2 family)
- Output: 256 bits (64 hex characters)
- Status: Secure, widely recommended
- Used for: Digital signatures, certificates, Bitcoin
SHA-256("Hello") = 185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969SHA-512
- Output: 512 bits (128 hex characters)
- Status: Secure
- Used for: When 256 bits isn't enough
SHA-3 (Keccak)
- Output: 224/256/384/512 bits
- Status: Latest standard, different design
- Used for: When SHA-2 alternative needed
BLAKE2/BLAKE3
- Output: Variable (up to 512 bits)
- Status: Secure, faster than SHA-2
- Used for: Performance-critical applications
Algorithm Comparison
| Algorithm | Output Size | Speed | Security | Use Case |
|---|---|---|---|---|
| MD5 | 128 bits | Fast | Broken | Checksums only |
| SHA-1 | 160 bits | Fast | Weak | Legacy only |
| SHA-256 | 256 bits | Medium | Strong | General purpose |
| SHA-512 | 512 bits | Medium | Strong | High security |
| SHA-3 | Variable | Medium | Strong | SHA-2 alternative |
| BLAKE3 | Variable | Very fast | Strong | Performance needs |
Implementation Examples
JavaScript (Browser)
async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message);
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
// Usage
const hash = await sha256('Hello World');
// "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e"Node.js
const crypto = require('crypto');
// SHA-256
const hash = crypto.createHash('sha256')
.update('Hello World')
.digest('hex');
// MD5
const md5 = crypto.createHash('md5')
.update('Hello World')
.digest('hex');
// HMAC (keyed hash)
const hmac = crypto.createHmac('sha256', 'secret-key')
.update('Hello World')
.digest('hex');Python
import hashlib
# SHA-256
hash_obj = hashlib.sha256(b'Hello World')
print(hash_obj.hexdigest())
# MD5
md5_hash = hashlib.md5(b'Hello World').hexdigest()
# SHA-512
sha512_hash = hashlib.sha512(b'Hello World').hexdigest()
# File hashing
def hash_file(filepath):
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdigest()Java
import java.security.MessageDigest;
import java.nio.charset.StandardCharsets;
public String sha256(String input) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
}Go
import (
"crypto/sha256"
"encoding/hex"
)
func sha256Hash(data string) string {
hash := sha256.Sum256([]byte(data))
return hex.EncodeToString(hash[:])
}Common Use Cases
1. Password Storage
Never store plain passwords. Hash them!
# ❌ Wrong: Plain SHA-256
hashed = hashlib.sha256(password.encode()).hexdigest()
# ✅ Right: Use bcrypt/Argon2 with salt
import bcrypt
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
# Verify
bcrypt.checkpw(password.encode(), hashed)2. File Integrity Verification
# Generate checksum
sha256sum file.zip > file.zip.sha256
# Verify
sha256sum -c file.zip.sha256// Node.js file hashing
const fs = require('fs');
const crypto = require('crypto');
function hashFile(path) {
return new Promise((resolve, reject) => {
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(path);
stream.on('data', data => hash.update(data));
stream.on('end', () => resolve(hash.digest('hex')));
stream.on('error', reject);
});
}3. Data Deduplication
# Find duplicate files
import os
import hashlib
from collections import defaultdict
def find_duplicates(directory):
hashes = defaultdict(list)
for root, dirs, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_hash = hash_file(filepath)
hashes[file_hash].append(filepath)
return {h: files for h, files in hashes.items() if len(files) > 1}4. API Request Signing
// HMAC for API authentication
const crypto = require('crypto');
function signRequest(method, path, body, secret) {
const timestamp = Date.now().toString();
const payload = `${method}${path}${timestamp}${JSON.stringify(body)}`;
const signature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return { timestamp, signature };
}5. Content Addressing
// Git-style content addressing
function contentAddress(data) {
const header = `blob ${data.length}\0`;
return sha1(header + data);
}Password Hashing: Special Considerations
Why Not Plain SHA-256?
- Too fast: Attackers can try billions per second
- No salt: Same password = same hash (rainbow tables)
- No iterations: Single computation
Proper Password Hashing
| Algorithm | Recommended | Notes |
|---|---|---|
| Argon2id | Yes | Winner of Password Hashing Competition |
| bcrypt | Yes | Time-tested, widely supported |
| scrypt | Yes | Memory-hard |
| PBKDF2 | OK | Use with high iterations |
| SHA-256 | No | Too fast for passwords |
// bcrypt example
const bcrypt = require('bcrypt');
// Hash password
const saltRounds = 12;
const hash = await bcrypt.hash(password, saltRounds);
// Verify password
const match = await bcrypt.compare(password, hash);# Argon2 example
from argon2 import PasswordHasher
ph = PasswordHasher()
hash = ph.hash("password")
ph.verify(hash, "password")HMAC: Keyed Hashing
HMAC (Hash-based Message Authentication Code) adds a secret key:
// HMAC-SHA256
const crypto = require('crypto');
function hmacSha256(message, key) {
return crypto
.createHmac('sha256', key)
.update(message)
.digest('hex');
}
// Use cases:
// - API authentication
// - Message integrity
// - Session tokensSecurity Best Practices
1. Use Strong Algorithms
// ❌ Don't use
const hash = md5(data); // Broken
const hash = sha1(data); // Deprecated
// ✅ Do use
const hash = sha256(data); // Good
const hash = sha3_256(data); // Also good2. Salt Your Hashes
// For passwords and sensitive data
const salt = crypto.randomBytes(16).toString('hex');
const hash = sha256(salt + password);
// Store both salt and hash3. Use Constant-Time Comparison
// ❌ Vulnerable to timing attacks
if (hash1 === hash2) { ... }
// ✅ Constant-time comparison
const crypto = require('crypto');
if (crypto.timingSafeEqual(Buffer.from(hash1), Buffer.from(hash2))) { ... }4. Don't Roll Your Own Crypto
// ❌ Custom hash combination
const hash = sha256(sha256(data) + sha256(key));
// ✅ Use established constructions
const hash = hmacSha256(data, key);Debugging and Verification
Online Verification
Always verify your implementation against known test vectors:
SHA-256("") = e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
SHA-256("abc") = ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015adCommand Line Tools
# Linux/Mac
echo -n "Hello" | sha256sum
echo -n "Hello" | md5sum
# OpenSSL
echo -n "Hello" | openssl dgst -sha256Conclusion
Hash functions are fundamental building blocks of security. Choose the right algorithm for your use case: SHA-256 for general purposes, Argon2/bcrypt for passwords, and HMAC when you need authentication.
Use our free Hash Generator to quickly compute hashes during development and verify your implementations.
Try Our Free Tools
Put these tips into practice with our free online tools. No signup required.
Explore Tools