Introduction
PBKDF2, which stands for Password-Based Key Derivation Function version 2, was published in 2000 as part of RFC 2898 (PKCS#5 v2.0) by RSA Laboratories. It was designed to address a fundamental weakness of plain hashing: passwords are short and predictable, so a hash of a password can be cracked with brute force in seconds. PBKDF2 slows down brute force by iterating the hash function many thousands of times. In this pbkdf2 java tutorial we will use the standard javax.crypto.SecretKeyFactory class to derive a strong key from a password.
PBKDF2 is specified in many standards including NIST SP 800-132. It is the password hashing algorithm in Apple's iOS keychain, in 1Password's older vault format, in WPA-WPA2 Wi-Fi networks (where it derives the session key from the Wi-Fi password), and in many database-driven web applications. For new applications, modern alternatives such as bcrypt, scrypt, and Argon2 are preferred because PBKDF2 is not memory-hard, but PBKDF2 with high iteration counts remains a secure and widely supported choice.
What is PBKDF2?
PBKDF2 is a key derivation function that takes a password, a salt, an iteration count, and a desired output length, and produces a deterministic pseudorandom key. The salt is a random value that prevents the same password from producing the same key in two different applications; the iteration count is a slowdown factor that makes brute force expensive; and the output length is the size of the derived key in bits.
The core construction is iterative HMAC. Each block of output is produced by repeatedly applying HMAC to the previous HMAC output, with the password as the HMAC key and the salt and block index as the message. The first HMAC output is HMAC(password, salt || blockIndex), the second is HMAC(password, firstOutput), and so on. The final key is the XOR of all intermediate HMAC outputs, which is why the algorithm is sometimes called "X-and-iterate".
Compared to a single SHA-256 of a password, PBKDF2 with 600,000 iterations is 600,000 times slower to compute, which means an attacker's brute force budget is 600,000 times more expensive. Compared to bcrypt, PBKDF2 is faster in software (which is bad because attackers benefit too). Compared to scrypt and Argon2, PBKDF2 is not memory-hard, so attackers can build specialized ASICs that compute it cheaply.
How PBKDF2 Works Step by Step
Suppose we want to derive a 32-byte (256-bit) key from the password "password123" with the 8-byte salt "01234567" and 1000 iterations.
Step 1: The salt is concatenated with a 4-byte big-endian block counter, starting at 1. So the first block's input is the salt followed by 0x00000001.
Step 2: Compute U1 = HMAC-SHA-256(password, salt || 0x00000001). This is the first HMAC output.
Step 3: Compute U2 = HMAC-SHA-256(password, U1). This is the second HMAC output, using the first as the message.
Step 4: Compute U3 = HMAC-SHA-256(password, U2), and continue for the specified number of iterations. Each iteration uses the previous HMAC output as the message.
Step 5: The block output is U1 XOR U2 XOR U3 XOR ... XOR Un. The XOR combines all intermediate HMAC outputs into a single 32-byte block. For a 32-byte derived key, we need only one block. For longer derived keys, we increment the block counter and repeat the process.
The reason the iteration count slows down brute force is that the attacker must run the full iteration chain for every password guess. If you set the iteration count to 600,000, the attacker needs to compute 600,000 HMACs for every guess, which makes the attack 600,000 times more expensive.
Java Program for PBKDF2 Password Based Key Derivation
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
public class Pbkdf2Demo {
public static void main(String[] args) throws Exception {
// 1. Generate a random 16-byte salt
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
System.out.println("Salt (b64): " + Base64.getEncoder().encodeToString(salt));
// 2. Choose parameters: 600,000 iterations, 256-bit output, HMAC-SHA-256
char[] password = "correct horse battery staple".toCharArray();
int iterations = 600_000;
int keyLengthBits = 256;
// 3. Build the spec and run PBKDF2
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLengthBits);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
SecretKey derivedKey = factory.generateSecret(spec);
byte[] keyBytes = derivedKey.getEncoded();
System.out.println("Iterations: " + iterations);
System.out.println("Key (hex) : " + HexFormat.of().formatHex(keyBytes));
System.out.println("Key (b64) : " + Base64.getEncoder().encodeToString(keyBytes));
// 4. Demonstrate verification: same password + salt + iterations = same key
PBEKeySpec spec2 = new PBEKeySpec(password, salt, iterations, keyLengthBits);
SecretKey derivedKey2 = factory.generateSecret(spec2);
boolean matches = java.security.MessageDigest.isEqual(
derivedKey.getEncoded(), derivedKey2.getEncoded());
System.out.println("Same key : " + matches);
// 5. Show timing: derivation should take measurable time
long start = System.nanoTime();
for (int i = 0; i < 5; i++) {
factory.generateSecret(new PBEKeySpec(password, salt, iterations, keyLengthBits));
}
long end = System.nanoTime();
System.out.println("Avg time : " + ((end - start) / 5_000_000) + " ms");
// 6. Clear the password from memory
java.util.Arrays.fill(password, '\u0000');
}
}
Code Explanation Line by Line
The first block generates a random 16-byte salt with SecureRandom. The salt is public; it does not need to be secret. Its purpose is to ensure that two different users with the same password get different derived keys, and that an attacker cannot use a precomputed rainbow table across many users. The salt should be at least 16 bytes long to defeat rainbow tables and should be unique per user.
PBEKeySpec is the javax.crypto data class that holds the parameters for password-based encryption. It takes a char array (not a String, because char arrays can be cleared), a salt byte array, an iteration count, and a key length in bits. The iteration count is the slowdown factor; 600,000 is roughly the right number for HMAC-SHA-256 in 2024-2026 to defeat commodity GPU attacks. The key length is the size of the output you want; 256 bits is the standard choice for AES-256.
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") returns a factory for PBKDF2 using HMAC-SHA-256 as the underlying hash. The Java algorithm name explicitly names the hash function because PBKDF2 can use any HMAC; PBKDF2WithHmacSHA1 is also available but is weaker due to SHA-1's known issues. PBKDF2WithHmacSHA512 is also available for stronger hashing.
The generateSecret method runs the full PBKDF2 algorithm and returns a SecretKey object whose getEncoded method gives the derived key bytes. This derived key can be used directly as an AES key or fed into another key-derivation step.
The fourth block demonstrates verification: the same password, salt, and iteration count produce the same derived key. This is how a login flow works: at registration time, you store the salt and the derived key; at login time, you re-run PBKDF2 with the user-supplied password and the stored salt, and compare the result to the stored derived key. Use MessageDigest.isEqual for the comparison so the timing is constant.
The fifth block shows the timing. Deriving a single key should take roughly 100 to 500 milliseconds on a modern CPU; if it is faster than 10 milliseconds your iteration count is too low. The 600,000 iteration count used here is appropriate for HMAC-SHA-256 in the 2024 to 2026 timeframe; OWASP recommends higher counts over time.
The sixth block clears the password from memory. Strings in Java are immutable and live in the string pool, so a password stored in a String may persist in memory indefinitely. A char array can be wiped by filling with null characters, which is what java.util.Arrays.fill does.
Sample Input and Output
Salt (b64): r2VzL9pQ2sF8tW5nC1xY7mB0hD6eA== Iterations: 600000 Key (hex) : 4b3c2d1a0e9f8a7b6c5d4e3f2a1b0c9d8e7f6a5b4c3d2e1f0a9b8c7d6e5f4a3b Key (b64) : S8wtGg6firtMXk48KhsMnY5/a1tMPR4QCpuMXWX0ojs= Same key : true Avg time : 387 ms
The exact key and timing will differ. The crucial fact is that the same inputs always produce the same key, and that the derivation takes measurable time.
Common Mistakes to Avoid
First, never use a low iteration count. OWASP recommends at least 600,000 iterations for HMAC-SHA-256 in 2023-2026. Counts below 1000 are effectively useless; counts below 100,000 are weak by modern standards. Increase the count as hardware improves.
Second, never reuse a salt across users. Each user must have a fresh random salt stored alongside their derived key. Reusing the salt lets an attacker build a rainbow table that defeats all users at once.
Third, never use PBKDF2 with HMAC-SHA-1 for new applications. While HMAC-SHA-1 has not been broken in practice, SHA-1 has, and compliance regimes require SHA-256 or stronger. Use PBKDF2WithHmacSHA256 or PBKDF2WithHmacSHA512.
Fourth, never store the password in a String. Strings are immutable in Java and cannot be wiped, so a memory dump may reveal the password. Always use char arrays and clear them with Arrays.fill after use.
Real-World Applications
PBKDF2 derives the master encryption key for 1Password's older vault format. Apple's iOS keychain uses PBKDF2 to derive encryption keys from the device passcode. WPA2 Wi-Fi networks use PBKDF2 to derive the session key from the Wi-Fi password. Django's default password hasher is PBKDF2 with SHA-256. Many legacy web applications still use PBKDF2 for password storage because it is available in every standard library.
For new applications, consider bcrypt, scrypt, or Argon2. These memory-hard KDFs are more resistant to specialized hardware attacks. PBKDF2 remains a defensible choice when you need cross-platform compatibility or when you cannot install a third-party library.
Conclusion
In this pbkdf2 java tutorial we used the standard javax.crypto.SecretKeyFactory class to derive a 256-bit key from a password using PBKDF2 with HMAC-SHA-256 and 600,000 iterations. We discussed why salt and high iteration counts are essential, and why char arrays are safer than Strings for passwords. PBKDF2 remains a solid choice for password-based key derivation when configured correctly.
Comments
Comments
Post a Comment