Hash functions are fundamental to software security. Whether you're verifying file integrity, storing passwords, or building blockchain applications, understanding hashing is essential.
What Is a Hash Function?
A hash function takes any input and produces a fixed-length output (the "digest"). Key properties:
- Deterministic: Same input always produces same output
- Fast: Computing the hash is quick
- One-way: You can't reverse a hash to get the input
- Collision-resistant: Finding two inputs with the same hash is extremely hard
- Avalanche effect: Small input change → completely different hash
Hash Algorithm Comparison
| Algorithm | Output Size | Speed | Security | Use Case |
|---|---|---|---|---|
| MD5 | 128-bit | Fast | Broken | Checksums only |
| SHA-1 | 160-bit | Fast | Weak | Legacy systems |
| SHA-256 | 256-bit | Medium | Strong | General purpose |
| SHA-512 | 512-bit | Medium | Strong | High security |
| BLAKE3 | 256-bit | Very fast | Strong | Modern apps |
Hashing in JavaScript
// Browser (Web Crypto API)
async function sha256(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
await sha256('hello'); // "2cf24dba5fb0a30e..."
// Node.js
const crypto = require('crypto');
const hash = crypto.createHash('sha256')
.update('hello')
.digest('hex');
Hashing in Python
import hashlib
# SHA-256
hash = hashlib.sha256(b'hello').hexdigest()
# "2cf24dba5fb0a30e..."
# MD5 (checksums only!)
md5 = hashlib.md5(b'hello').hexdigest()
# File hash
def hash_file(path, algo='sha256'):
h = hashlib.new(algo)
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(8192), b''):
h.update(chunk)
return h.hexdigest()
Password Hashing (Do This Right!)
Never use MD5/SHA for passwords. Use these instead:
// Node.js with bcrypt
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash('password', 12);
const isValid = await bcrypt.compare('password', hash);
// Argon2 (recommended)
const argon2 = require('argon2');
const hash = await argon2.hash('password');
const isValid = await argon2.verify(hash, 'password');
# Python with bcrypt
import bcrypt
hashed = bcrypt.hashpw(b'password', bcrypt.gensalt(12))
valid = bcrypt.checkpw(b'password', hashed)
HMAC (Hash-based Message Authentication)
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'secret-key')
.update('message')
.digest('hex');
Used in: API authentication, webhook verification, JWT signatures.
File Integrity Verification
# Generate checksum
sha256sum file.zip > file.zip.sha256
# Verify
sha256sum -c file.zip.sha256
Try It Online
Generate MD5, SHA-1, SHA-256, SHA-512 hashes instantly with our free Hash Generator — no installation, no data sent to servers.
What hash algorithm does your project use? Share below!
Top comments (0)