snippetjavascriptModeratepending
Password hashing -- bcrypt, argon2, and never roll your own
Viewed 0 times
bcryptargon2password hashsaltcost factortiming attack
nodejs
Problem
Storing passwords in plain text or with simple hash functions (MD5, SHA256) is a critical security vulnerability. Need secure password storage that resists brute-force and rainbow table attacks.
Solution
Use bcrypt or argon2id for password hashing. These are intentionally slow, include a salt, and have configurable cost factors. Never use MD5/SHA for passwords.
Code Snippets
Secure password hashing with bcrypt
// Node.js with bcrypt
import bcrypt from 'bcrypt';
const SALT_ROUNDS = 12; // ~250ms on modern hardware
async function hashPassword(password) {
return bcrypt.hash(password, SALT_ROUNDS);
}
async function verifyPassword(password, hash) {
return bcrypt.compare(password, hash);
// bcrypt.compare is timing-safe
}
// Registration
const hash = await hashPassword('user_password');
await db.insert({ email, passwordHash: hash });
// Login
const user = await db.findByEmail(email);
if (!user || !(await verifyPassword(password, user.passwordHash))) {
throw new Error('Invalid credentials');
// Don't reveal which field was wrong
}Revisions (0)
No revisions yet.