Hash Passwords Java Guide to Argon2 bcrypt and PBKDF2
Hash passwords in Java with Argon2id, bcrypt or PBKDF2 using Spring Security's PasswordEncoder, salts, work factors, upgrades and what never to use.

A database of passwords will leak sooner or later. What an attacker can do with it depends on how you stored them. Fast hashes such as MD5 or SHA-256 can be tested at billions of guesses per second on a GPU. Password hashing algorithms are built to be slow and memory hungry.
What to use
| Algorithm | Notes |
|---|---|
| Argon2id | Winner of the password hashing competition, memory hard, OWASP's first choice |
| bcrypt | Mature, cost factor, truncates input at 72 bytes |
| scrypt | Memory hard, available in Spring Security |
| PBKDF2 | Standard and FIPS-approved, needs a very high iteration count (hundreds of thousands) |
| MD5, SHA-1, SHA-256 alone | Do not use for passwords |
A hash function with a salt but no work factor is still too fast. The slow part is the point.
With Spring Security
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}String stored = encoder.encode("correct horse battery staple");
// {bcrypt}$2a$10$N9qo8uLOickgx2ZMRZoMye...
boolean ok = encoder.matches(candidate, stored);The delegating encoder prefixes the hash with the algorithm id ({bcrypt}), so matches picks the right one. When you want to move to Argon2, new passwords use the new default, and old hashes still verify. Re-hash on successful login when encoder.upgradeEncoding(stored) returns true. That lets you migrate users silently.
To pick Argon2 explicitly:
PasswordEncoder encoder = new Argon2PasswordEncoder(16, 32, 1, 1 << 16, 3);
// saltLength, hashLength, parallelism, memory in KiB (64 MiB), iterationsSpring Security's Argon2 and scrypt encoders use Bouncy Castle, so add org.bouncycastle:bcprov-jdk18on. Check OWASP's current parameter recommendations, for example a minimum of 19 MiB memory with 2 iterations for Argon2id, and use stronger settings if the server can afford them.
Without a framework
The JDK includes PBKDF2:
static String hash(char[] password) throws GeneralSecurityException {
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
PBEKeySpec spec = new PBEKeySpec(password, salt, 600_000, 256);
byte[] key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
return "pbkdf2$600000$" + Base64.getEncoder().encodeToString(salt) + "$" + Base64.getEncoder().encodeToString(key);
}
static boolean verify(char[] password, String stored) throws GeneralSecurityException {
String[] parts = stored.split("\\$");
int iterations = Integer.parseInt(parts[1]);
byte[] salt = Base64.getDecoder().decode(parts[2]);
byte[] expected = Base64.getDecoder().decode(parts[3]);
byte[] actual = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
.generateSecret(new PBEKeySpec(password, salt, iterations, expected.length * 8)).getEncoded();
return MessageDigest.isEqual(expected, actual); // constant-time comparison
}Use char[] so the password can be cleared, a random 16-byte salt for each password, the iteration count stored with the hash, and MessageDigest.isEqual for a comparison that does not leak timing. For bcrypt and Argon2 on plain Java, use a maintained library such as Bouncy Castle or de.mkammerer:argon2-jvm.
Work factor
Choose the parameters so that one hash takes about 100 to 500 ms on your hardware under normal load. Measure on the production server class. The cost applies to every login, so a login endpoint needs rate limiting: an attacker can use the hashing cost for denial of service. Raise the factor over time as hardware improves, and use upgradeEncoding.
Other points
- Pepper. A secret key mixed in outside the database adds protection if only the database leaks. Keep it in a key store and treat rotation carefully.
- Length. Allow long passwords and passphrases. bcrypt truncates at 72 bytes, so pre-hashing is sometimes used, with care.
- Do not log passwords or hashes, and do not return them from APIs.
- Reset tokens are credentials: random, single-use, short lived and stored as hashes.
- Multi-factor authentication reduces dependence on the password.
Upgrade hashes as users log in
The best parameters of today are weak in five years, and old users' hashes stay as they were. Spring Security's DelegatingPasswordEncoder stores the algorithm in the hash and can re-hash on login, so the whole table improves without a reset email:
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}Hashes are stored as {bcrypt}$2a$10$... or {argon2@SpringSecurity_v5_8}.... After a successful check, ask whether the stored hash is outdated and replace it:
if (encoder.matches(raw, user.getPasswordHash())) {
if (encoder.upgradeEncoding(user.getPasswordHash())) {
user.setPasswordHash(encoder.encode(raw));
users.save(user);
}
}upgradeEncoding returns true when the algorithm or cost is below the current default. Users who never log in keep the old hash, so run a sweep for accounts that stay inactive: expire their passwords and require a reset.
Pick the cost from a measurement
A cost that is too low protects nothing and one that is too high lets an attacker slow your login with a few requests. Measure on the production hardware:
Argon2PasswordEncoder encoder = Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
long start = System.nanoTime();
for (int i = 0; i < 20; i++) {
encoder.encode("correct horse battery staple");
}
System.out.printf("%.0f ms per hash%n", (System.nanoTime() - start) / 20 / 1e6);Aim for roughly 100 to 500 ms per hash on the login path. At 250 ms and 8 cores, the server verifies about 32 logins per second, and the rest queue or fail. Tune up until the login rate you need is just covered, and put a rate limit in front so that failed attempts cannot exhaust the CPU. Repeat the measurement whenever the instance type changes.
The bcrypt length limit
bcrypt uses only the first 72 bytes of the password, and ignores the rest, so two passwords that share the first 72 bytes hash the same. Long passphrases and multibyte characters reach it faster than expected. Spring Security's encoder rejects longer values in recent versions, and older code silently truncates. If you must keep bcrypt, hash the password with SHA-256 first and Base64-encode the digest, which keeps the length constant. Argon2 and PBKDF2 do not have the limit.
A pepper adds a second secret
A pepper is a secret value mixed into the hash and stored outside the database, in a key vault or an environment variable. A leaked database dump then lacks the key needed to test guesses. Apply it with an HMAC before the password hash:
byte[] mac = hmacSha256(pepper, password.getBytes(StandardCharsets.UTF_8));
String hash = encoder.encode(Base64.getEncoder().encodeToString(mac));The cost is rotation: changing the pepper invalidates every hash unless a version marker is stored, so keep a key id with each hash. A pepper helps only when the database and the application are compromised separately, so it does not replace a good work factor.
What a login endpoint needs besides hashing
| Control | Reason |
|---|---|
| Rate limit per account and per address | Slows online guessing |
| The same message for unknown user and wrong password | Does not reveal which accounts exist |
| Constant-time comparison, supplied by the encoder | Avoids timing leaks |
| Compare against a dummy hash for unknown users | Equalises response time |
| Check against a breached password list | Stops the most common choices at registration |
| Multi-factor authentication | Limits the value of a stolen password |
Hashing protects the stored data after a breach, and the controls above protect the login before one.
Reviewing authentication code with a short list
Password code is small and gets reviewed rarely. A short list helps: the encoder is a framework one and not hand-written, the work factor was measured on production hardware, hashes carry an algorithm prefix so they can be upgraded, the login path is rate-limited, error messages do not reveal whether an account exists, and passwords never appear in logs, URLs or exception messages.
Run the list at every change to the login code, and once a year on the whole path. Most breaches that involve passwords trace back to one of these six items.
Where this does not apply
API keys and tokens with high entropy can be stored as a fast hash such as SHA-256, since brute-forcing them is infeasible. Login mechanics for frameworks are covered in Spring Security 401 errors, Jakarta Security and Vaadin with Spring Security. The reference is the OWASP Password Storage Cheat Sheet, and the Spring Security password storage documentation describes the encoders.


