TL;DR
Hashing is a one-way transformation that turns data into a fixed-length string. Unlike encryption, you cannot reverse a hash to get the original data. This is perfect for passwords because you never need to see the original, just verify it matches. Use bcrypt or Argon2 for passwords. Never use MD5 or SHA-1 as they are too fast and have vulnerabilities.
The Simple Explanation
When a user creates a password, you hash it and store the hash. When they log in, you hash what they entered and compare it to the stored hash. If they match, the password is correct. You never store or know the actual password.
import bcrypt from 'bcrypt';
// When user creates password const hash = await bcrypt.hash(password, 10); // Store hash in database
// When user logs in const isValid = await bcrypt.compare(password, storedHash);
Hashing Algorithms
| Algorithm | Use For Passwords? | Notes |
|---|---|---|
| Argon2 | Yes (recommended) | Winner of Password Hashing Competition |
| bcrypt | Yes | Widely used, well-tested |
| scrypt | Yes | Memory-hard, good alternative |
| SHA-256 | No | Too fast, use for checksums |
| MD5 | No | Broken, never use |
Why Slow Hashing Matters
Fast algorithms let attackers try billions of passwords per second. Slow algorithms (bcrypt, Argon2) are intentionally slow, making brute force attacks impractical. Checking one password takes milliseconds for users but years for attackers trying millions.
Which hashing algorithm should I use for passwords?
Use bcrypt, Argon2, or scrypt for passwords. These are designed to be slow, making brute force attacks expensive. Never use MD5 or SHA-1 for passwords as they are too fast and have known vulnerabilities. Argon2 is the current recommended algorithm, but bcrypt is widely supported and still secure.
What is a salt in password hashing?
A salt is random data added to a password before hashing. It ensures that identical passwords produce different hashes. Without salts, attackers can use precomputed rainbow tables to crack passwords. Modern algorithms like bcrypt automatically generate and store salts.
Can hashed passwords be reversed?
No, hashing is a one-way function. You cannot mathematically reverse a hash to get the original password. However, attackers can try to guess passwords by hashing common passwords and comparing. This is why you need slow algorithms (bcrypt, Argon2) and salts to make guessing expensive.