Encryption vs Hashing — Explained with Examples
Encryption transforms data into ciphertext using a key and is reversible, while hashing produces a fixed-length fingerprint that cannot be reversed.
Encryption and Hashing serve fundamentally different purposes. Encryption protects data confidentiality by making it unreadable without a key. Hashing verifies data integrity by producing a unique, irreversible digest.
Key Differences
| Feature | Encryption | Hashing |
|---|---|---|
| Reversible | Yes (with key) | No |
| Output length | Same as input | Fixed length |
| Key | Required | Not used |
| Purpose | Confidentiality | Integrity |
| Example | AES, RSA | SHA-256, MD5 |
Encryption: Two-Way
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
// Encrypt
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
// Decrypt (reversible with the key)
function decrypt(encrypted) {
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
const message = 'Credit card: 4111-1111-1111-1111';
const encrypted = encrypt(message);
console.log('Encrypted:', encrypted);
console.log('Decrypted:', decrypt(encrypted)); // Original message restored
Hashing: One-Way
const crypto = require('crypto');
function hash(password) {
return crypto.createHash('sha256').update(password).digest('hex');
}
const password = 'MyP@ssw0rd';
const hashed = hash(password);
console.log('Hash:', hashed);
// e.g., "a591a6d40bf420404a011733cfaff873c5adf1a4ab71c9e7a5e2d1f3e7e5d1f3"
// Verification: hash the input and compare
function verify(input, storedHash) {
return hash(input) === storedHash;
}
console.log(verify('MyP@ssw0rd', hashed)); // true
console.log(verify('wrong', hashed)); // false
Real-World Analogy
Encryption is like a lockbox. You put a letter inside, lock it with a key, and send it. The recipient uses their key to unlock it and read the letter. Hashing is like a fingerprint. Your fingerprint uniquely identifies you, but you can’t reconstruct your face from it. If someone claims they’re Alice, you check their fingerprint against Alice’s stored fingerprint — but you can’t derive Alice’s appearance from the print.
When to Use Each
- Encryption: credit card numbers, messages, files in transit (TLS) or at rest
- Hashing: passwords (use bcrypt/argon2, not raw SHA), file integrity checks, digital signatures
Related Terms
TLS/SSL, HTTPS, PKI, Authentication vs Authorization
Related Tutorial
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro