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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A per-password random salt stops precomputed rainbow-table attacks and makes identical passwords hash differently.
- 2A high iteration count deliberately slows derivation so brute-force guessing stays expensive.
- 3Comparing hashes in constant time prevents attackers from learning secrets through response timing.
Related explainers
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
public final class Slugifier { private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]"); private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
Building a URL slugifier in Java
regex
unicode-normalization
string-processing
Intermediate
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
java
@Controller public class BookController { private final BookService bookService;
Solving GraphQL N+1 with batch mapping in Spring
graphql
n+1-problem
batching
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/salted-password-hashing-with-pbkdf2-in-java-explained-java-6435/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.