Password Hashing Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Password Hashing runs in O(n) time and O(1) space, in Java as in every other language.
- ✓The JDK gives you PBKDF2 only: javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") fed a javax.crypto.spec.PBEKeySpec built from a char[], a salt, an iteration count and a key length, with generateSecret(spec).getEncoded() returning the derived bytes.
- ✓char[] from the servlet or DTO boundary all the way down, cleared in a finally block; a reviewer will flag any String-typed password parameter on sight.
- ✓The Java trap: A password that ever lands in a String is unclearable: String is immutable with a private final backing array, so there is no supported way to overwrite it, and it sits in the heap until collection, showing up verbatim in any heap dump, core file or OOM snapshot taken meanwhile.
- ✓SunJCE implements PBKDF2 in Java rather than delegating to a native library, and Spring's BCrypt is pure Java too, so the same iteration count costs measurably more CPU here than an OpenSSL-backed implementation would.
What Password Hashing actually is
Password Hashing in Java: what you actually reach for
Java implementation
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
public final class Passwords {
private static final int ITERATIONS = 600_000;
private static final int KEY_BITS = 256;
private static final SecureRandom RNG = new SecureRandom();
private Passwords() {}
public static byte[] newSalt() {
byte[] salt = new byte[16];
RNG.nextBytes(salt);
return salt;
}
public static byte[] derive(char[] password, byte[] salt, int iterations)
throws Exception {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, KEY_BITS);
try {
SecretKeyFactory f =
SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
return f.generateSecret(spec).getEncoded();
} finally {
spec.clearPassword();
}
}
public static String encode(char[] password) throws Exception {
try {
byte[] salt = newSalt();
byte[] dk = derive(password, salt, ITERATIONS);
Base64.Encoder b64 = Base64.getEncoder();
return "pbkdf2-sha256$" + ITERATIONS + "$"
+ b64.encodeToString(salt) + "$" + b64.encodeToString(dk);
} finally {
Arrays.fill(password, '\0');
}
}
public static boolean verify(char[] password, String stored)
throws Exception {
try {
String[] parts = stored.split("\\$");
if (parts.length != 4 || !"pbkdf2-sha256".equals(parts[0])) {
return false;
}
int iterations;
try {
iterations = Integer.parseInt(parts[1]);
} catch (NumberFormatException e) {
return false;
}
Base64.Decoder b64 = Base64.getDecoder();
byte[] salt = b64.decode(parts[2]);
byte[] expected = b64.decode(parts[3]);
return MessageDigest.isEqual(
derive(password, salt, iterations), expected);
} finally {
Arrays.fill(password, '\0');
}
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Password Hashing?
The JDK gives you PBKDF2 only: javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") fed a javax.crypto.spec.PBEKeySpec built from a char[], a salt, an iteration count and a key length, with generateSecret(spec).getEncoded() returning the derived bytes. PBEKeySpec exposes clearPassword(). Salt comes from java.security.SecureRandom, and java.security.MessageDigest.isEqual is the documented constant-time byte comparison. There is no bcrypt, scrypt or Argon2 in the JDK: Spring Security supplies BCryptPasswordEncoder, Argon2PasswordEncoder and DelegatingPasswordEncoder, and Bouncy Castle supplies the primitives.
What is the most common Java mistake when implementing Password Hashing?
A password that ever lands in a String is unclearable: String is immutable with a private final backing array, so there is no supported way to overwrite it, and it sits in the heap until collection, showing up verbatim in any heap dump, core file or OOM snapshot taken meanwhile. A literal password in a test can additionally be interned into the constant pool and live for the process lifetime. That is precisely why PBEKeySpec takes char[] and offers clearPassword(); most code defeats it by calling request.getParameter(...).toCharArray(), which copies out of a String that already leaked.
How does Password Hashing actually perform in Java?
SunJCE implements PBKDF2 in Java rather than delegating to a native library, and Spring's BCrypt is pure Java too, so the same iteration count costs measurably more CPU here than an OpenSSL-backed implementation would. Calibrate on the JVM you deploy, with the same GC and -XX flags: SecretKeyFactory instances are not thread-safe and getInstance() does a provider lookup per call, so a benchmark that constructs the factory inside the timed loop measures JCA provider dispatch rather than PBKDF2; hoist it and use JMH's warmup iterations rather than a hand-rolled loop. The work is CPU-bound and pins a servlet container request thread for its whole duration, so the thread pool, not the algorithm, is what falls over first. Time complexity is O(n) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.