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
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 steps
ruby
require "openssl" require "base32" class TOTP
How TOTP one-time codes work in Ruby
hmac
authentication
totp
Intermediate
7 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.