30 Mins

4. Password Hashing (Bcrypt, Argon2, PBKDF2)

Why Fast Hashes Fail

Standard cryptographic hashes like SHA-256 are designed for speed. In data integrity applications, speed is a virtue. However, in password storage, speed is a vulnerability. Because SHA-256 is extremely fast, modern GPUs can compute billions of hashes per second, allowing an attacker to brute-force a password database with ease.

When an attacker gains access to a hashed password file, they don't need to crack the cipher; they simply compare their guessed hashes against the stolen database until a match is found. If the algorithm performs too quickly, an attacker can test every combination of characters in a dictionary attack in mere seconds.

Security Operator Note: Never use cryptographic hash functions (SHA, MD5, BLAKE) for password storage. Use key derivation functions designed specifically for passwords.
Text
# Example of how fast a standard SHA-256 hash can be computed in a loop using OpenSSL
time for i in {1..1000}; do echo -n 'password' | openssl dgst -sha256; done

Salting and Pepper: Defeating Rainbow Tables

A salt is a random value added to a password before hashing. It prevents attackers from using pre-computed tables of hashes (rainbow tables) because the resulting hash becomes unique to that specific salt. Even if two users have the same password, their hashes will differ due to the unique salt.

A pepper is a secret key stored separately from the database (e.g., in a secure environment variable). It acts as an additional layer of security; even if the database is leaked, the attacker still requires the pepper to begin brute-forcing.

MechanismFunction
SaltUnique, random per-user string stored in DB to prevent pre-computation.
PepperSecret global string stored externally to provide defense-in-depth.
Security Operator Note: Always store the salt alongside the hash in your database; the salt does not need to be secret, but it must be unique.
Python 3
import hashlib
import os

def hash_with_salt(password, salt):
    combined = salt + password.encode()
    return hashlib.sha256(combined).hexdigest()

user_salt = os.urandom(16).hex()
print(f'Hash: {hash_with_salt("mySecretPassword", user_salt.encode())}')

Key Derivation Functions (KDFs)

KDFs like Bcrypt and Argon2 are designed to be slow. They implement a work factor that forces the CPU to perform extensive calculations for every password attempt. Argon2, the winner of the Password Hashing Competition, is memory-hard, meaning it requires a significant amount of RAM, making it incredibly expensive for attackers to use dedicated hardware like FPGAs or ASICs to speed up cracking.

By increasing the time and memory cost, we make brute-forcing exponentially more difficult for an attacker while keeping the delay imperceptible for a single user logging in.

Security Operator Note: Bcrypt is the industry standard for general use, but use Argon2id if your infrastructure supports it for better resistance against hardware-based attacks.
Python 3
import bcrypt

password = b"supersecret"
# Generate salt and hash
salted_hash = bcrypt.hashpw(password, bcrypt.gensalt(rounds=12))

# Verification
if bcrypt.checkpw(password, salted_hash):
    print("Password match!")

Implementing Argon2 in Python

Argon2id is currently recommended for new deployments. It provides the best protection against both side-channel attacks and GPU cracking. Using the argon2-cffi library, you can easily set memory, time, and parallelism parameters.

The following code demonstrates setting up a robust hashing process. Note that Argon2id manages the salt internally, which simplifies development and avoids common salt implementation errors.

Security Operator Note: Always verify passwords using the official library's verify function, which performs constant-time comparisons to prevent timing attacks.
Python 3
from argon2 import PasswordHasher

ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)
hash = ph.hash("my_password")
print(f"Encoded hash: {hash}")

try:
    ph.verify(hash, "my_password")
    print("Verification successful")
except Exception as e:
    print(f"Verification failed: {e}")

Knowledge Check

Ready to test your understanding of 4. Password Hashing (Bcrypt, Argon2, PBKDF2)?

Back