Course contentsShow
← Security
Lesson 305 of 3,0527. Randomness and Key ManagementFree lesson

Key Stretching and Derivation

Using PBKDF2, bcrypt, scrypt, and Argon2 to derive cryptographic keys from passwords with appropriate iteration counts and salts.

Key Stretching and Derivation

What you'll learn: How to transform weak passwords into strong cryptographic keys using specialized algorithms that defend against brute-force attacks.

The Problem with Passwords as Keys

Remember from earlier lessons that good cryptographic keys need high entropy—but human passwords are terrible at this. "Password123" has far less randomness than a proper 128-bit key. If you directly hash a password to create a key, attackers can test millions of guesses per second on modern hardware.

What is Key Stretching?

Key stretching deliberately makes key derivation slow and memory-hard to compute. Think of it like adding speed bumps: legitimate users barely notice one login taking 100 milliseconds instead of 1 millisecond, but attackers testing a billion passwords now need 100,000 seconds instead of 1,000.

The Tools: PBKDF2, bcrypt, scrypt, and Argon2

These algorithms build on concepts you've learned (hashing, HMACs, iteration) but apply them specially:

  • PBKDF2 repeatedly applies HMAC thousands of times (iteration count). More iterations = slower = harder to crack.
  • bcrypt uses iterations plus an expensive internal algorithm designed to resist specialized hardware attacks.
  • scrypt adds memory requirements, making it expensive to parallelize on GPUs or custom chips.
  • Argon2 (the modern standard) combines iteration, memory-hardness, and parallelism resistance. It won the Password Hashing Competition in 2015.

Essential Components

All these algorithms require:

  • Salt: A unique random value per password (prevents rainbow tables and parallel attacks)
  • Iteration count: How many times to repeat expensive operations (balance security vs performance)
  • Output length: The size of the derived key you need

Choosing Parameters

Set iteration counts high enough that derivation takes 100ms-1s on your hardware. Update these values as computers get faster. Always use random salts from your CSPRNG.

Key Takeaway: Use Argon2 (or scrypt/bcrypt as fallbacks) with proper salts and iteration counts to derive cryptographic keys from passwords—never hash passwords directly with fast algorithms like SHA-256.