CKTIS / Java
Security and password hashing
Security and password hashing: Java security requires trust-boundary validation, least privilege, and platform cryptography; password hashing should use a slow KDF rather than raw MessageDigest.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
securityJava security requires trust-boundary validation, least privilege, and platform cryptography; password hashing should use a slow KDF rather than raw MessageDigest.
Generate a fresh random salt per password, derive with PBKDF2, and use MessageDigest.isEqual for constant-time comparison of equal-length derived values.
Do not store passwords, use fast SHA-256 for password hashing, or copy the example’s fixed salt into production.
The example creates a deterministic demonstration token with fixed demo-salt only for repeatable stdout; production needs SecureRandom, unique salt, and a tuned KDF cost.
PBKDF2 with demo-salt yields token 1835cac9f59580aa39ed2cf0d68c84f2, and MessageDigest.isEqual compares its clone and prints true.
Examples
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HexFormat;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class Main {
static byte[] derive(char[] password, byte[] salt) throws Exception {
PBEKeySpec spec = new PBEKeySpec(password, salt, 1_000, 128);
try {
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
} finally {
spec.clearPassword();
}
}
public static void main(String[] args) throws Exception {
byte[] token = derive("correct horse".toCharArray(), "demo-salt".getBytes(StandardCharsets.UTF_8));
System.out.println(HexFormat.of().formatHex(token));
System.out.println(MessageDigest.isEqual(token, token.clone()));
}
}
Result
1835cac9f59580aa39ed2cf0d68c84f2 true
PBKDF2 with demo-salt yields token 1835cac9f59580aa39ed2cf0d68c84f2, and MessageDigest.isEqual compares its clone and prints true.