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.

JavaAuth Jwt

Code

snippet
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

FAQ

What does PBKDF2 Hashing With SecretKeyFactory print when run?
The script runs standalone; its 4 labeled outputs include `salt:`, `hash bytes:`, `same password:`.