Difficulty: Beginner
What is the difference between hashing and encryption, and when would you use each?
Hashing is a one-way function that turns any input into a fixed-size digest; you cannot get the original back, only check whether another input produces the same digest. Encryption is two-way: data is scrambled with a key and can be decrypted by someone holding the right key. Use hashing when you only need to verify something (passwords, file integrity) and encryption when you need the original data back later (card details, Aadhaar numbers, messages).
| Aspect | Hashing | Encryption |
|---|---|---|
| Reversible? | No | Yes, with the key |
| Key involved? | No (HMAC uses a key for authentication) | Yes |
| Output size | Fixed (SHA-256 is always 256 bits) | Roughly the size of the input |
| Main goal | Integrity and verification | Confidentiality |
| Examples | SHA-256, SHA-3, BLAKE3; for passwords Argon2id, bcrypt, scrypt | AES-256-GCM, ChaCha20-Poly1305, RSA, ECIES |
| Typical use | Storing passwords, checksums, deduplication, digital signatures | HTTPS traffic, encrypting PII at rest, disk encryption |
TLS uses both: asymmetric cryptography to agree on a key, then symmetric encryption for the actual traffic. Prefer authenticated encryption modes like AES-GCM, which detect tampering, over older modes like AES-CBC without a MAC. Never use ECB mode.
import crypto from 'node:crypto';
// Hashing: one-way, fixed length
const digest = crypto.createHash('sha256').update('hello').digest('hex');
console.log(digest.length); // 64 hex chars = 256 bits
// Encryption: AES-256-GCM, reversible with the key
const key = crypto.randomBytes(32); // in production: from a KMS
const iv = crypto.randomBytes(12); // unique per message
const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
const ct = Buffer.concat([cipher.update('4111-xxxx', 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag(); // detects tampering
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
const pt = Buffer.concat([decipher.update(ct), decipher.final()]).toString();
console.log(pt); // '4111-xxxx'
The hash cannot be reversed, while the GCM ciphertext decrypts back to the original and the auth tag fails decryption if anything was modified.
Hashing, Symmetric Encryption, Asymmetric Encryption, AES-GCM, Argon2, Encoding