Appearance
Passwords and Hashing
35. What is the difference between hashing, encryption, and encoding?
The short answer
Encoding changes the format of data so it can travel safely, such as Base64 or URL encoding. It uses no key, and anyone can reverse it, so it protects nothing. Encryption scrambles data with a key so only someone with the key can turn it back, such as AES for files or TLS for traffic. Hashing turns any input into a fixed-size fingerprint that cannot be turned back, such as SHA-256. Use encoding for transport, encryption for data you must read again, and hashing for checking data, including passwords, without keeping the original.
| Encoding | Encryption | Hashing | |
|---|---|---|---|
| Purpose | Change format | Keep secret | Fingerprint and verify |
| Needs a key | No | Yes | No |
| Reversible | Yes, by anyone | Yes, with the key | No |
| Same input, same output | Yes | Usually not, a random IV is added | Yes, unless salted |
| Example | Base64, %20 in URLs | AES-GCM, RSA | SHA-256, Argon2 |
The same text through all three, in Node:
ts
import { createHash, createCipheriv, randomBytes } from 'node:crypto'
const text = 'card ending 4242'
Buffer.from(text).toString('base64') // (1)
// 'Y2FyZCBlbmRpbmcgNDI0Mg=='
const key = randomBytes(32), iv = randomBytes(12)
const cipher = createCipheriv('aes-256-gcm', key, iv) // (2)
const encrypted = Buffer.concat([cipher.update(text), cipher.final()])
// different bytes every run, because the key and IV are random
createHash('sha256').update(text).digest('hex') // (3)
// always the same 64 hex characters for this exact text- Base64. Anyone can decode this back. It is not protection.
- AES-256-GCM encryption. Without
key, the bytes are useless. GCM also adds a tag that detects tampering. - SHA-256 hash. No key exists to reverse it. Change one character and the whole output changes.
The classic interview trap: "We Base64-encode the password before storing it." That is plain text with extra steps.
Hashes used for passwords are a special kind. SHA-256 is designed to be fast, which is good for checking files and bad for passwords: an attacker can try billions of guesses a second. Passwords need a deliberately slow hash (question 38).
36. Why are password hashes salted?
The short answer
A salt is a random value, unique to each user, mixed into the password before hashing and stored next to the hash. Without salts, two users with the same password get the same hash, so cracking one cracks both. An attacker can also use precomputed tables of hashes for common passwords, called rainbow tables, to crack a whole database at once. With a unique salt, every hash is different, precomputed tables are useless, and the attacker must attack each user separately. Modern password hashes like bcrypt and Argon2 generate and store the salt for you.
What a stored bcrypt value contains:
text
$2b$12$R9h/cIPz0gi.URNNX3kh2OPST9/PgBkqquzi.Ss7KIUgO2t0jWMUW
│ │ └──── 22 characters of salt ─────┘└──── 31 characters of hash ────┘
│ └ cost factor 12
└ algorithm version 2bThe salt is not secret. It sits right beside the hash. Its job is to be unique, not hidden.
What a salt does not do: make a weak password strong. sunshine1 is still found quickly when the attacker targets one user. That is why the hash must also be slow, and why you check new passwords against breached-password lists.
37. What is peppering in password storage?
The short answer
A pepper is one extra secret value, shared by all passwords, that is mixed in before or after hashing and stored outside the database, such as in a vault or KMS. If an attacker steals only the database, for example through SQL injection, the hashes are useless to them without the pepper. It is optional defence in depth, not a replacement for salting and a slow hash. The usual way is to run the password through an HMAC with the pepper first, then hash that result with Argon2. Another way is to encrypt the finished hash with a KMS key.
ts
import { createHmac } from 'node:crypto'
import argon2 from 'argon2'
const pepper = (password: string) =>
createHmac('sha256', config.PASSWORD_PEPPER).update(password).digest('base64') // (1)
async function hashPassword(password: string) {
return argon2.hash(pepper(password), { type: argon2.argon2id }) // (2)
}
async function checkPassword(stored: string, attempt: string) {
return argon2.verify(stored, pepper(attempt)) // (3)
}- Mix in the pepper with an HMAC, a keyed fingerprint. The pepper is loaded from the vault, never from the database.
- Then the normal salted, slow hash. The database stores only this Argon2 string.
- Checking a login repeats both steps. An attacker who stole only the database cannot even test a guess, because every guess must first go through the HMAC, and that needs the pepper.
A common mistake is to store the plain Argon2 hash and a peppered copy side by side. The attacker simply ignores the peppered copy and cracks the plain one. The pepper must be part of the only value you store.
The cost of a pepper: rotation is hard. You cannot re-pepper a password you do not know. Teams handle this by storing a pepper version beside each hash and re-hashing with the new pepper the next time each user logs in.
| Salt | Pepper | |
|---|---|---|
| Per user or shared | Unique per user | One for all |
| Stored where | Next to the hash | Vault or KMS, never the database |
| Secret? | No | Yes |
| Required? | Yes | Optional extra layer |
38. How do bcrypt and Argon2 compare?
The short answer
Both are deliberately slow, salted password hashes with an adjustable cost. bcrypt, from 1999, is slow in CPU time only and has a 72-byte input limit; longer passwords are cut off. Argon2id, the 2015 Password Hashing Competition winner, is slow in both time and memory. That matters because attackers crack with graphics cards, which have huge compute but little memory per core, so a memory-hard hash costs them far more. OWASP recommends Argon2id first, with at least 19 MiB of memory, 2 iterations and 1 thread. Use bcrypt with a cost of at least 10 where Argon2 is not available.
| bcrypt | Argon2id | |
|---|---|---|
| Year | 1999 | 2015 |
| Costly in | CPU time | CPU time and memory |
| Resists GPU cracking | Moderately | Strongly |
| Input limit | 72 bytes | None in practice |
| Tuning | One cost factor | Memory, iterations, parallelism |
| OWASP minimum | Cost 10 | m=19 MiB, t=2, p=1 |
Choosing the cost. Aim for about a quarter to half a second per hash on your login server. Slow enough to hurt an attacker making billions of guesses. Fast enough that a real login does not feel slow. Measure on your own hardware.
ts
import argon2 from 'argon2'
const hash = await argon2.hash(password, {
type: argon2.argon2id, // (1)
memoryCost: 19_456, // (2)
timeCost: 2,
parallelism: 1,
})
const ok = await argon2.verify(hash, attempt) // (3)
if (ok && argon2.needsRehash(hash, { memoryCost: 65_536, timeCost: 3 })) { // (4)
await users.updateHash(userId, await argon2.hash(attempt, { type: argon2.argon2id, memoryCost: 65_536, timeCost: 3 }))
}- The id variant, which resists both GPU cracking and side-channel attacks.
- Memory in kibibytes: 19,456 KiB is 19 MiB, the OWASP minimum.
- Verify reads the salt and settings from the stored string, so you never store them separately.
- Upgrade old hashes at login. When you raise the cost later, the next successful login is the only moment you have the plain password, so re-hash then.
The bcrypt 72-byte trap. bcrypt silently ignores everything after 72 bytes. A long passphrase, or a pre-hash scheme that adds a long prefix, can make two different passwords hash the same. Argon2 does not have this limit.
Slow hashing is a denial-of-service risk. Each login burns real CPU and memory. Rate limit the login route (the rate limiting question), and keep hashing off the event loop. The argon2 and bcrypt packages already run it on the libuv thread pool.
39. Why should passwords be hashed rather than reversibly encrypted?
The short answer
Because you never need to read a password back. You only need to check that a login attempt matches, and a hash can do that. If passwords are encrypted, the key must live somewhere your app can reach, so an attacker who breaches the app gets the key and every password at once. Insiders with the key can also read them. With a slow, salted hash, there is nothing to decrypt: an attacker must guess each password one at a time, at great cost. A site that can email you your old password is storing it wrongly.
Login, with hashing:
- Signup: store
argon2.hash(password). The password itself is discarded. - Login: compute the check with the stored salt and settings, and compare.
- Match: the user typed the right password. Nobody, including you, learned what it was.
Why encryption fails here:
| Threat | Encrypted passwords | Hashed passwords |
|---|---|---|
| Database and app server stolen | All passwords readable, key is on the server | Each must be cracked separately |
| Insider with access | Can decrypt any password | Cannot read any |
| Users reuse passwords elsewhere | Their other accounts fall too | Strong ones stay safe |
| Legal and audit stance | A finding | Expected practice |
When reversible encryption is right: secrets your system must use, not verify. An API key for a vendor, or an OAuth refresh token you must send later, are encrypted with a KMS-held key, because you must read them back to use them.
"Forgot password" therefore means a reset, never a reminder. Email a single-use, short-lived reset link. Store only the hash of the reset token. Expire it after one use or about 30 minutes.