PBKDF2 Hashing With SecretKeyFactory
Derive password hashes with PBKDF2WithHmacSHA256, a per-user random salt, and a high iteration count, then compare digests in constant time.
Code
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class Main {
private static final int ITERATIONS = 210_000;
private static final int KEY_BITS = 256;
private static byte[] derive(char[] password, byte[] salt) throws Exception {
// PBKDF2 hashing with a per-user salt and a tunable iteration count
PBEKeySpec spec = new PBEKeySpec(password, salt, ITERATIONS, KEY_BITS);
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
return factory.generateSecret(spec).getEncoded();
} finally {
spec.clearPassword(); // 及时清掉 PBEKeySpec 持有的口令副本
}
}
public static void main(String[] args) throws Exception {
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
byte[] stored = derive("correct horse battery staple".toCharArray(), salt);
byte[] same = derive("correct horse battery staple".toCharArray(), salt);
byte[] wrong = derive("wrong password".toCharArray(), salt);
System.out.println("salt: " + Base64.getEncoder().encodeToString(salt));
System.out.println("hash bytes: " + stored.length);
System.out.println("same password: " + MessageDigest.isEqual(stored, same));
System.out.println("wrong password: " + MessageDigest.isEqual(stored, wrong));
}
}What the code does
The working surface is the class Main — everything else is wiring.
Applying it
The demo output is labeled (salt:, hash bytes:, same password:), so every printed line maps back to its originating operation.
Statements that matter
return factory.generateSecret(spec).getEncoded();
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.
FAQ
- What does PBKDF2 Hashing With SecretKeyFactory print when run?
- The script runs standalone; its 4 labeled outputs include `salt:`, `hash bytes:`, `same password:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.