3 Hours

3. Password Hashing & Credential Security

Password Security

Passwords are the most common authentication method, but also the most vulnerable if not handled correctly. This module covers why we hash passwords, what salting is, and how to use bcrypt correctly.

NEVER store passwords in plain text. If your database is compromised, plain text passwords give attackers direct access to user accounts.

What is Hashing?

Hashing is a one-way function. You can turn a password into a hash, but you cannot turn the hash back into the password.

Text
Plain Text:  "password123"
     ↓
Hash Function (bcrypt)
     ↓
Hash: "$2b$10$CwTycUXWue0Thq9StjUM0uJQQvK7hq6WqE9ZqWqE9ZqWqE9ZqWq"
Key Insight: You cannot decrypt a hash. When a user logs in, you hash the password they typed and compare the hashes. If they match, the password was correct.

What is a Salt?

A salt is random data added to the password BEFORE hashing. This ensures that identical passwords produce completely different hashes.

Text
User A: "password123" + salt_ABC → Hash: 7d8f9a...
User B: "password123" + salt_XYZ → Hash: 3k2j9h...

Same password, completely different hashes!
Why salts matter: Without salts, an attacker could pre-compute hashes for common passwords (rainbow table). Salts make pre-computation useless.

bcrypt: The Industry Standard

bcrypt is designed specifically for password hashing. It automatically handles salting and is intentionally slow to resist brute-force attacks.

JavaScript
// Node.js example - hashing a password
const bcrypt = require('bcrypt');
const saltRounds = 12;

async function hashPassword(plainPassword) {
    const hash = await bcrypt.hash(plainPassword, saltRounds);
    console.log(hash);  // $2b$12$KIXxGx...
    return hash;
}

async function verifyPassword(plainPassword, storedHash) {
    const isValid = await bcrypt.compare(plainPassword, storedHash);
    return isValid;  // true or false
}
Java
// Java/Spring Boot example
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

String hash = encoder.encode("password123");
boolean isValid = encoder.matches("password123", hash);
Why slow is good: A fast hash like SHA-256 can compute billions of guesses per second. bcrypt with rounds=12 takes ~0.2 seconds per guess — attackers are dramatically slowed down.

The Registration Flow

When a user registers, you hash their password and store only the hash. The plain password is never stored anywhere.

JavaScript
async function registerUser(email, plainPassword) {
    // Step 1: Hash the password
    const hashedPassword = await bcrypt.hash(plainPassword, 12);

    // Step 2: Store ONLY the hash in database
    await db.users.create({
        email: email,
        passwordHash: hashedPassword  // NOT the plain password!
    });

    // Never store or log the plain password
}

The Login Flow

When a user logs in, you hash the password they typed and compare it to the stored hash.

JavaScript
async function loginUser(email, plainPassword) {
    // Step 1: Look up user by email
    const user = await db.users.findByEmail(email);

    if (!user) {
        return { success: false, error: 'Invalid credentials' };
    }

    // Step 2: Compare the provided password with stored hash
    const isValid = await bcrypt.compare(plainPassword, user.passwordHash);

    if (isValid) {
        return { success: true, userId: user.id };
    } else {
        return { success: false, error: 'Invalid credentials' };
    }
}
Use the same error message for both cases! Invalid credentials (not User not found or Wrong password) prevents attackers from discovering which emails are registered.

Password Policy Best Practices

Text
DO:
- Enforce minimum length (8+ characters, preferably 12+)
- Block common passwords ("password", "123456", "qwerty")
- Implement rate limiting on login attempts
- Use account lockout after multiple failures
- Use bcrypt with rounds=12 or higher

DON'T:
- Enforce complex composition (uppercase, number, special char)
- Force frequent password changes (NIST no longer recommends this)
- Use security questions (answers are often guessable or public)
- Send passwords in email or store in logs
NIST Guidelines: The National Institute of Standards and Technology no longer recommends periodic password expiration. It leads to weaker passwords like Spring2024! → Summer2024!

Knowledge Check

Ready to test your understanding of 3. Password Hashing & Credential Security?

Back