Java Password Hashing
Java password hashing turns a password into a fixed value that you can store and check later, without ever storing the password itself. If your database leaks, attackers get only the hashes, and a good password hash makes guessing the original passwords slow and expensive.
In this lesson you will see why a plain SHA-256 hash is not enough, then build proper password storage with a random salt and PBKDF2 using only the standard JDK. The final example is a complete password service with registration, login and automatic hash upgrades. It uses ideas from Java Security and Java Secure Coding.
Hashing vs Encryption for Passwords
Encryption can be reversed with a key. Hashing cannot be reversed at all. For passwords you want hashing, because the server never needs the original password back; it only needs to check whether a login attempt produces the same hash.
| Approach | Reversible? | Safe for passwords? | Why |
|---|---|---|---|
| Plain text | Yes | No | Anyone who reads the database sees every password |
| Encryption (AES) | Yes, with the key | No | A stolen key reveals every password |
| Fast hash (SHA-256) | No | No | Too fast; equal passwords give equal hashes |
| Salted fast hash | No | Weak | Unique per user, but still billions of guesses per second on a GPU |
| Password hash (PBKDF2, bcrypt, scrypt, Argon2) | No | Yes | Salted and deliberately slow |
Why a Plain SHA-256 Hash Is Not Enough
SHA-256 is a great general hash, but it was designed to be fast. That is exactly what an attacker wants when guessing passwords. It also gives the same output for the same input, so two users with the same password have the same stored value.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
public class PlainHashProblem {
static String sha256(String text) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of().formatHex(digest.digest(text.getBytes(StandardCharsets.UTF_8)));
}
public static void main(String[] args) throws Exception {
// Two users who picked the same password get the same stored value
System.out.println("asha : " + sha256("password123"));
System.out.println("ravi : " + sha256("password123"));
// A plain hash is also extremely fast to compute
long start = System.nanoTime();
for (int attempt = 0; attempt < 1_000_000; attempt++) {
sha256("guess" + attempt);
}
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println("1,000,000 guesses took about " + (millis < 2000 ? "1-2 seconds" : millis / 1000 + " seconds"));
}
}
Output (the timing depends on your computer):
asha : ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
ravi : ef92b778bafe771e89245b89ecbc08a44a4e166c06659911881f383d4473e94f
1,000,000 guesses took about 1-2 seconds
How it works:
sha256hashes the UTF-8 bytes of the text and prints them as hex withHexFormat.- Both users get exactly the same 64-character value, so cracking one password cracks both. Precomputed tables of common password hashes (rainbow tables) also work directly against such values.
- A single CPU core computes about a million SHA-256 hashes in a second or two. A GPU computes billions per second.
Adding a Random Salt
A salt is a random value created for each password and stored next to its hash. Because every user has a different salt, equal passwords produce different hashes, and precomputed tables become useless. The salt is not secret.
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
public class SaltDemo {
private static final SecureRandom RANDOM = new SecureRandom();
static byte[] newSalt() {
byte[] salt = new byte[16]; // 128 bits
RANDOM.nextBytes(salt);
return salt;
}
static byte[] saltedSha256(String password, byte[] salt) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(salt);
return digest.digest(password.getBytes(StandardCharsets.UTF_8));
}
public static void main(String[] args) throws Exception {
byte[] ashaSalt = newSalt();
byte[] raviSalt = newSalt();
byte[] ashaHash = saltedSha256("password123", ashaSalt);
byte[] raviHash = saltedSha256("password123", raviSalt);
Base64.Encoder base64 = Base64.getEncoder();
System.out.println("Salt length: " + ashaSalt.length + " bytes -> " + base64.encodeToString(ashaSalt).length() + " Base64 chars");
System.out.println("Same password, same hash? " + MessageDigest.isEqual(ashaHash, raviHash));
System.out.println("Recompute with the stored salt matches? "
+ MessageDigest.isEqual(ashaHash, saltedSha256("password123", ashaSalt)));
}
}
Output:
Salt length: 16 bytes -> 24 Base64 chars
Same password, same hash? false
Recompute with the stored salt matches? true
How it works:
SecureRandomcreates 16 unpredictable bytes for each user. Never usejava.util.Randomfor this, because its output can be predicted.digest.update(salt)feeds the salt in before the password, so the result depends on both.- Even with the same password, Asha and Ravi have different hashes. To check a login, the server reads the stored salt and repeats the calculation.
MessageDigest.isEqualcompares two byte arrays in constant time, so the time taken does not reveal how many bytes matched.
Note: Salting fixes the "equal passwords" problem but not the speed problem. You still need a slow algorithm, which is what PBKDF2 adds.
Java Password Hashing With PBKDF2
PBKDF2 (Password-Based Key Derivation Function 2) repeats an HMAC thousands of times. The JDK includes it as PBKDF2WithHmacSHA256, available through SecretKeyFactory. You choose the salt, the number of iterations and the output length.
PBEKeySpec spec = new PBEKeySpec(char[] password, byte[] salt, int iterations, int keyLengthBits);
byte[] hash = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
| Parameter | Recommended value | Purpose |
|---|---|---|
password | char[] | Can be wiped after use, unlike String |
salt | 16 random bytes | Unique per password |
iterations | 600,000 for PBKDF2-HMAC-SHA256 (OWASP guidance) | Makes every guess slow |
keyLengthBits | 256 | Matches the SHA-256 output size |
import java.security.spec.KeySpec;
import java.util.HexFormat;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class Pbkdf2Basics {
public static void main(String[] args) throws Exception {
char[] password = "password123".toCharArray();
// A fixed salt is used ONLY so this demo prints the same hash every time
byte[] salt = HexFormat.of().parseHex("8f3a1c5e7b9d2f4a6c8e0b1d3f5a7c9e");
int iterations = 600_000;
int keyLengthBits = 256;
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keyLengthBits);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
long start = System.nanoTime();
byte[] hash = factory.generateSecret(spec).getEncoded();
long millis = (System.nanoTime() - start) / 1_000_000;
spec.clearPassword(); // wipe the copy held by the spec
System.out.println("Hash bytes : " + hash.length);
System.out.println("Hash (hex) : " + HexFormat.of().formatHex(hash));
System.out.println("Slow enough: " + (millis >= 50 ? "yes" : "no") + " (one hash takes tens to hundreds of ms)");
}
}
Output:
Hash bytes : 32
Hash (hex) : 86481430f88250c89715615655c1a59b2b863e40575bfe0882b02e3136ca2985
Slow enough: yes (one hash takes tens to hundreds of ms)
How it works:
PBEKeySpecbundles the password, salt, iteration count and desired length.generateSecretruns HMAC-SHA256 600,000 times and returns a 32-byte (256-bit) result.- One hash now takes a noticeable fraction of a second. A real user logs in once and does not notice, but an attacker trying millions of guesses is slowed down by the same factor.
spec.clearPassword()wipes the spec's internal copy of the password.
Storing the Salt, Iterations and Hash Together
To verify a password later, you need the same salt and the same iteration count. Store everything in one string, in a format such as algorithm$iterations$salt$hash. This also lets you raise the iteration count in the future without breaking old accounts.
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class StoredFormat {
private static final String ALGORITHM = "PBKDF2WithHmacSHA256";
private static final int ITERATIONS = 600_000;
private static final SecureRandom RANDOM = new SecureRandom();
static byte[] pbkdf2(char[] password, byte[] salt, int iterations) throws Exception {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, 256);
try {
return SecretKeyFactory.getInstance(ALGORITHM).generateSecret(spec).getEncoded();
} finally {
spec.clearPassword();
}
}
// Format: pbkdf2_sha256$<iterations>$<salt>$<hash>
static String hashPassword(char[] password) throws Exception {
byte[] salt = new byte[16];
RANDOM.nextBytes(salt);
byte[] hash = pbkdf2(password, salt, ITERATIONS);
Base64.Encoder base64 = Base64.getEncoder().withoutPadding();
return "pbkdf2_sha256$" + ITERATIONS + "$" + base64.encodeToString(salt) + "$" + base64.encodeToString(hash);
}
static boolean verifyPassword(char[] attempt, String stored) throws Exception {
String[] parts = stored.split("\\$");
int iterations = Integer.parseInt(parts[1]);
byte[] salt = Base64.getDecoder().decode(parts[2]);
byte[] expectedHash = Base64.getDecoder().decode(parts[3]);
byte[] actualHash = pbkdf2(attempt, salt, iterations);
return MessageDigest.isEqual(expectedHash, actualHash); // constant-time comparison
}
public static void main(String[] args) throws Exception {
String stored = hashPassword("Correct-Horse-42".toCharArray());
String[] parts = stored.split("\\$");
System.out.println("Stored parts: " + parts[0] + " | " + parts[1] + " | salt "
+ parts[2].length() + " chars | hash " + parts[3].length() + " chars");
System.out.println("Correct password: " + verifyPassword("Correct-Horse-42".toCharArray(), stored));
System.out.println("Wrong password : " + verifyPassword("correct-horse-42".toCharArray(), stored));
System.out.println("Hash again, same string? " + stored.equals(hashPassword("Correct-Horse-42".toCharArray())));
}
}
Output:
Stored parts: pbkdf2_sha256 | 600000 | salt 22 chars | hash 43 chars
Correct password: true
Wrong password : false
Hash again, same string? false
How it works:
hashPasswordcreates a fresh salt, runs PBKDF2 and joins the four parts with$. Base64 without padding keeps the string short: 16 salt bytes become 22 characters, and 32 hash bytes become 43 characters.verifyPasswordsplits the stored string, decodes the salt and expected hash, and runs PBKDF2 again with the stored iteration count.- Passwords are case sensitive, so
correct-horse-42fails. - Hashing the same password twice gives two different strings because of the random salt. That is why you always verify with the stored salt instead of comparing two new hashes.
Note: Libraries offer other strong password hashes. Spring Security has
BCryptPasswordEncoderandArgon2PasswordEncoder, and Argon2id is the first choice in current OWASP guidance. PBKDF2 is the best option when you must use only the JDK or need FIPS-approved algorithms.
Real-World Example: A Password Service With Hash Upgrades
This class works like the password part of a real login system. It enforces a minimum password length, wipes passwords after use, protects against username discovery through timing, and upgrades old hashes to a higher iteration count when users log in.
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class PasswordService {
private static final String PREFIX = "pbkdf2_sha256";
private static final int SALT_BYTES = 16;
private static final int HASH_BITS = 256;
private static final int MIN_LENGTH = 12;
private final int currentIterations;
private final SecureRandom random = new SecureRandom();
private final Map<String, String> userStore = new HashMap<>(); // stands in for a database table
// Hash of a random password, used to keep timing equal for unknown usernames
private final String dummyHash;
PasswordService(int currentIterations) throws Exception {
this.currentIterations = currentIterations;
this.dummyHash = hash("unused-dummy-password".toCharArray());
}
void register(String username, char[] password) throws Exception {
try {
if (password.length < MIN_LENGTH) {
throw new IllegalArgumentException("Password must be at least " + MIN_LENGTH + " characters");
}
userStore.put(username, hash(password));
System.out.println("Registered " + username);
} finally {
Arrays.fill(password, '\0');
}
}
boolean login(String username, char[] password) throws Exception {
try {
String stored = userStore.get(username);
// Always run one PBKDF2 calculation, even for unknown users
boolean matches = verify(password, stored != null ? stored : dummyHash) && stored != null;
if (matches && needsRehash(stored)) {
userStore.put(username, hash(password)); // upgrade silently on login
System.out.println(" (upgraded hash for " + username + " to " + currentIterations + " iterations)");
}
return matches;
} finally {
Arrays.fill(password, '\0');
}
}
String storedHash(String username) {
return userStore.get(username);
}
private String hash(char[] password) throws Exception {
byte[] salt = new byte[SALT_BYTES];
random.nextBytes(salt);
byte[] hash = pbkdf2(password, salt, currentIterations);
Base64.Encoder encoder = Base64.getEncoder().withoutPadding();
return String.join("$", PREFIX, String.valueOf(currentIterations),
encoder.encodeToString(salt), encoder.encodeToString(hash));
}
private boolean verify(char[] password, String stored) throws Exception {
String[] parts = stored.split("\\$");
if (parts.length != 4 || !parts[0].equals(PREFIX)) {
return false;
}
byte[] salt = Base64.getDecoder().decode(parts[2]);
byte[] expected = Base64.getDecoder().decode(parts[3]);
return MessageDigest.isEqual(expected, pbkdf2(password, salt, Integer.parseInt(parts[1])));
}
private boolean needsRehash(String stored) {
return Integer.parseInt(stored.split("\\$")[1]) < currentIterations;
}
private static byte[] pbkdf2(char[] password, byte[] salt, int iterations) throws Exception {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, HASH_BITS);
try {
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
} finally {
spec.clearPassword();
}
}
public static void main(String[] args) throws Exception {
// Version 1 of the app used fewer iterations
PasswordService oldService = new PasswordService(100_000);
oldService.register("asha", "Lotus-Chennai-2026".toCharArray());
String oldHash = oldService.storedHash("asha");
// Version 2 raises the cost; existing hashes are carried over
PasswordService service = new PasswordService(600_000);
service.userStore.put("asha", oldHash);
service.register("ravi", "Blue-Kettle-Morning".toCharArray());
try {
service.register("kumar", "short".toCharArray());
} catch (IllegalArgumentException e) {
System.out.println("Rejected kumar: " + e.getMessage());
}
System.out.println("asha, old hash iterations: " + service.storedHash("asha").split("\\$")[1]);
System.out.println("asha login (correct): " + service.login("asha", "Lotus-Chennai-2026".toCharArray()));
System.out.println("asha, new hash iterations: " + service.storedHash("asha").split("\\$")[1]);
System.out.println("ravi login (wrong) : " + service.login("ravi", "blue-kettle-morning".toCharArray()));
System.out.println("ghost login : " + service.login("ghost", "anything-at-all".toCharArray()));
}
}
Output:
Registered asha
Registered ravi
Rejected kumar: Password must be at least 12 characters
asha, old hash iterations: 100000
(upgraded hash for asha to 600000 iterations)
asha login (correct): true
asha, new hash iterations: 600000
ravi login (wrong) : false
ghost login : false
How it works:
- Registration.
registerrejects passwords shorter than 12 characters, hashes the rest and stores the result. Thefinallyblock wipes thechar[]even when an exception is thrown. - Old hashes. Asha registered with an older version of the app that used 100,000 iterations. Her stored string still says
100000, so the service knows how to verify it. - Login and upgrade. When Asha logs in with the correct password,
needsRehashsees that 100,000 is lower than the current 600,000. The service hashes her password again with a new salt and saves the stronger hash. This is the only moment the server has the plain password, so upgrades can only happen at login. - Wrong password. Ravi's attempt differs only in letter case, so PBKDF2 produces a different hash and
MessageDigest.isEqualreturnsfalse. - Unknown users. For
ghost, there is no stored hash, but the service still runs PBKDF2 againstdummyHash. Without this, a login for an unknown name would return instantly, and an attacker could time responses to find which usernames exist. - Constant-time checks. Every comparison uses
MessageDigest.isEqual, and the result for an unknown user is forced tofalsewith&& stored != null.