java 61 lines · 7 steps

Salted password hashing with PBKDF2 in Java

A password hasher that derives a slow, salted key and verifies it without leaking timing information.

Explained by highlit
1package com.example.security;
2 
3import javax.crypto.SecretKeyFactory;
4import javax.crypto.spec.PBEKeySpec;
5import java.security.SecureRandom;
6import java.security.spec.KeySpec;
7import java.util.Base64;
8 
9public final class PasswordHasher {
10 
11 private static final String ALGORITHM = "PBKDF2WithHmacSHA256";
12 private static final int ITERATIONS = 120_000;
13 private static final int SALT_BYTES = 16;
14 private static final int KEY_BITS = 256;
15 
16 private final SecureRandom random = new SecureRandom();
17 
18 public String hash(char[] password) {
19 byte[] salt = new byte[SALT_BYTES];
20 random.nextBytes(salt);
21 byte[] hash = pbkdf2(password, salt, ITERATIONS);
22 return ITERATIONS + ":" + encode(salt) + ":" + encode(hash);
23 }
24 
25 public boolean verify(char[] password, String stored) {
26 String[] parts = stored.split(":");
27 if (parts.length != 3) {
28 return false;
29 }
30 int iterations = Integer.parseInt(parts[0]);
31 byte[] salt = Base64.getDecoder().decode(parts[1]);
32 byte[] expected = Base64.getDecoder().decode(parts[2]);
33 byte[] actual = pbkdf2(password, salt, iterations);
34 return constantTimeEquals(expected, actual);
35 }
36 
37 private byte[] pbkdf2(char[] password, byte[] salt, int iterations) {
38 try {
39 KeySpec spec = new PBEKeySpec(password, salt, iterations, KEY_BITS);
40 SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
41 return factory.generateSecret(spec).getEncoded();
42 } catch (Exception e) {
43 throw new IllegalStateException("Unable to derive password hash", e);
44 }
45 }
46 
47 private boolean constantTimeEquals(byte[] a, byte[] b) {
48 if (a.length != b.length) {
49 return false;
50 }
51 int diff = 0;
52 for (int i = 0; i < a.length; i++) {
53 diff |= a[i] ^ b[i];
54 }
55 return diff == 0;
56 }
57 
58 private String encode(byte[] data) {
59 return Base64.getEncoder().encodeToString(data);
60 }
61}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A per-password random salt stops precomputed rainbow-table attacks and makes identical passwords hash differently.
  2. 2A high iteration count deliberately slows derivation so brute-force guessing stays expensive.
  3. 3Comparing hashes in constant time prevents attackers from learning secrets through response timing.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Salted password hashing with PBKDF2 in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code