Script Valley
Web Security Fundamentals for Developers
Authentication and Session SecurityLesson 4.1

How to hash passwords correctly: bcrypt, Argon2, and why MD5 is broken

password hashing vs encryption, salting, bcrypt cost factor, Argon2id, rainbow table attacks, GPU cracking, why MD5/SHA1 are wrong for passwords

Password Hashing

Password hashing and verification diagram

Passwords must be hashed before storage using an algorithm specifically designed for password hashing. General-purpose hashes like MD5 and SHA-256 are too fast—modern GPUs can compute billions of them per second, enabling brute force attacks against your entire user database if it's leaked.

Why MD5 and SHA1 Are Wrong

MD5 and SHA-256 are designed to be fast. An attacker with a leaked database and a modern GPU can compute 10+ billion MD5 hashes per second. A bcrypt hash with cost factor 12 takes ~250ms to compute—slowing brute force by a factor of millions.

Bcrypt: The Standard Choice

const bcrypt = require('bcrypt');
const SALT_ROUNDS = 12; // Adjust so hashing takes ~250ms on your hardware

// Hash on registration
async function hashPassword(plaintext) {
  return bcrypt.hash(plaintext, SALT_ROUNDS);
}

// Compare on login
async function verifyPassword(plaintext, hash) {
  return bcrypt.compare(plaintext, hash); // Returns boolean
}

// Usage
const hash = await hashPassword('userpassword');
await User.create({ email, password: hash });

// On login:
const valid = await verifyPassword(req.body.password, user.password);
if (!valid) return res.status(401).json({ error: 'Invalid credentials' });

Argon2: The Modern Standard

const argon2 = require('argon2');

const hash = await argon2.hash(password); // Argon2id by default
const valid = await argon2.verify(hash, password);

Argon2id is the winner of the 2015 Password Hashing Competition and the current OWASP recommendation. It's resistant to GPU attacks (memory-hard) and side-channel attacks. Both bcrypt and Argon2 are acceptable; Argon2id is preferred for new projects.

Up next

How JWTs work and the security mistakes developers make with them

Sign in to track progress