1 Hour

13. Passwords & Cryptography

Security

If your database has a column called password and it contains values like password123 or qwerty — your application is critically and immediately dangerous. Every week, major companies suffer data breaches. When hackers steal a database, the first thing they do is harvest the passwords. If those passwords are stored in plain text, every single user's account on every other website they use is now compromised. This module is not optional knowledge — it is a professional and ethical responsibility.

Why You Must NEVER Store Plain-Text Passwords

Here are the concrete risks of plain-text password storage:

  • Database breach: Any SQL injection vulnerability, any malicious employee, any backup file left unsecured — instantly exposes every user's password.
  • Password reuse: Studies show over 65% of people reuse passwords. Stealing your database gives attackers access to users' email, banking, and social media accounts.
  • Legal liability: GDPR in Europe and data protection laws in many countries make storing passwords in plain text a regulatory violation that results in massive fines.
  • Trust destruction: Once it's revealed your company stored passwords in plain text, that reputation damage is permanent.
The Golden Rule:

Never store the password. Store a one-way cryptographic transformation of it that can never be reversed.

Why Simple Hashing Is Also Not Enough

Your first instinct might be to hash the password with MD5 or SHA-256. This is better than plain text — but still dangerously insecure for passwords. Here's why:

  • Rainbow tables: Attackers precompute a massive lookup table of millions of common passwords and their hashes. If your hash is in the table, the password is instantly known. SHA256(password123) is always the same hash, and it's in every rainbow table.
  • Speed is an enemy: SHA-256 can compute billions of hashes per second on modern GPU hardware. A brute-force attack against a leaked SHA-256 database is trivially fast.

The solution requires two things: salting and purposefully slow hashing algorithms.

Salting

A salt is a long, random string generated uniquely for every user and appended to their password before hashing. This means even if two users have the identical password cat123, they produce completely different hashes because each salt is different. It makes rainbow table attacks completely ineffective.

Text
User 1: salt = "k9fJ2!xQ8mR7" → hash("k9fJ2!xQ8mR7" + "cat123") = "a3b7f2..."
User 2: salt = "p4wZ6$nY1oV3" → hash("p4wZ6$nY1oV3" + "cat123") = "9c2e1a..."

bcrypt — The Industry Standard for Password Hashing

bcrypt was specifically designed for hashing passwords. Unlike SHA-256 (built for speed), bcrypt is intentionally slow. It has a configurable work factor (called rounds or cost) that controls how many iterations of the algorithm run. More rounds = slower = harder to brute-force.

bcrypt also handles salting automatically — you don't manage the salt yourself. It generates a random salt, incorporates it into the hash computation, and stores the salt inside the resulting hash string. When verifying, bcrypt extracts the salt from the stored hash and re-runs the algorithm.

JavaScript
const bcrypt = require('bcrypt');

app.post('/auth/register', async (req, res) => {
    const { email, password } = req.body;
    
    if (password.length < 8) {
        return res.status(400).json({ error: 'Password must be at least 8 characters' });
    }
    
    const SALT_ROUNDS = 12;
    const passwordHash = await bcrypt.hash(password, SALT_ROUNDS);
    
    const user = await prisma.user.create({
        data: { email, passwordHash }
    });
    
    res.status(201).json({ message: 'Account created', userId: user.id });
});

app.post('/auth/login', async (req, res) => {
    const { email, password } = req.body;
    const user = await prisma.user.findUnique({ where: { email } });
    
    const dummyHash = '$2b$12$invalidHashThatWillAlwaysFail......................';
    const hashToCheck = user ? user.passwordHash : dummyHash;
    
    const isValid = await bcrypt.compare(password, hashToCheck);
    
    if (!user || !isValid) {
        return res.status(401).json({ error: 'Invalid email or password' });
    }
    
    const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET);
    res.json({ token });
});

Password Hashing in Python

Python 3
import bcrypt

def register_user(email: str, password: str):
    if len(password) < 8:
        raise ValueError("Password must be at least 8 characters")
    
    password_bytes = password.encode('utf-8')
    salt = bcrypt.gensalt(rounds=12)
    password_hash = bcrypt.hashpw(password_bytes, salt)
    
    return password_hash.decode('utf-8')

def verify_password(plain_password: str, stored_hash: str) -> bool:
    return bcrypt.checkpw(
        plain_password.encode('utf-8'),
        stored_hash.encode('utf-8')
    )

Password Reset — The Secure Way

When users forget their password, how do you reset it without exposing sensitive information? Never email the password itself (you can't — you don't have it). Never email a permanent link. The correct approach uses a short-lived cryptographic token:

JavaScript
const crypto = require('crypto');

app.post('/auth/forgot-password', async (req, res) => {
    const { email } = req.body;
    const user = await prisma.user.findUnique({ where: { email } });
    
    if (!user) {
        return res.json({ message: 'If that email exists, a reset link was sent.' });
    }
    
    const resetToken = crypto.randomBytes(32).toString('hex');
    const tokenHash = crypto.createHash('sha256').update(resetToken).digest('hex');
    
    await prisma.user.update({
        where: { id: user.id },
        data: {
            resetTokenHash:    tokenHash,
            resetTokenExpires: new Date(Date.now() + 15 * 60 * 1000)
        }
    });
    
    const resetUrl = `https://yourapp.com/reset-password?token=${resetToken}`;
    await sendEmail(user.email, 'Password Reset', `Click here: ${resetUrl}`);
    
    res.json({ message: 'If that email exists, a reset link was sent.' });
});

Security Best Practices Summary

Always use bcrypt (or Argon2)

bcrypt for most apps. Argon2id is the newer recommendation — more resistant to GPU attacks.

12 salt rounds minimum

10 was standard in 2015. As hardware gets faster, increase rounds. 12 is current best practice.

Never reveal which field is wrong

Invalid email or password — not email not found or wrong password.

Rate limit login attempts

After 5 failed attempts, lock the account or add a CAPTCHA. Use express-rate-limit.

Short-lived reset tokens

15 minutes maximum. Hash the token in the database. One-time use only.

Minimum 8 chars, check lists

Check against the HaveIBeenPwned API to reject known-breached passwords.

Knowledge Check

Ready to test your understanding of 13. Passwords & Cryptography?

Back