What is PBKDF2?
Password-Based Key Derivation Function 2 (PBKDF2) is a cryptographic standard designed to reduce vulnerabilities to brute-force attacks. It applies a pseudorandom function, such as HMAC, to an input password along with a salt value, repeating the process many times to produce a secure derived key.
Why is Password Stretching Important?
Modern graphics cards (GPUs) can guess billions of passwords per second. If an application only hashes a password once (e.g., a simple SHA-256 hash), an attacker can easily crack it using a dictionary attack. PBKDF2 mitigates this by introducing iterations (password stretching). By forcing the CPU to hash the password hundreds of thousands of times, it artificially slows down the derivation process. This millisecond delay is unnoticeable to a normal user logging in, but computationally devastating for an attacker trying to brute-force millions of hashes.
How to implement PBKDF2 in JavaScript
You can generate secure keys natively in the browser without importing massive NPM libraries by utilizing the Web Crypto API:
async function derivePBKDF2Key(password, saltString) {
const encoder = new TextEncoder();
// 1. Import the raw password
const keyMaterial = await window.crypto.subtle.importKey(
"raw",
encoder.encode(password),
{ name: "PBKDF2" },
false,
["deriveBits", "deriveKey"]
);
// 2. Derive the bits using 210,000 iterations
const derivedBits = await window.crypto.subtle.deriveBits(
{
name: "PBKDF2",
salt: encoder.encode(saltString),
iterations: 210000,
hash: "SHA-512"
},
keyMaterial,
256 // Output 32 bytes (256 bits) for AES-256
);
return derivedBits;
}