1package dev.rafex.ether.crypto.password;
29import java.security.MessageDigest;
30import javax.crypto.SecretKeyFactory;
31import javax.crypto.spec.PBEKeySpec;
32import java.util.Arrays;
39 private static final String ALGORITHM =
"PBKDF2WithHmacSHA256";
41 private final int derivedKeyBytes;
50 if (derivedKeyBytes < 16) {
51 throw new IllegalArgumentException(
"derivedKeyBytes demasiado pequeño");
53 this.derivedKeyBytes = derivedKeyBytes;
66 public boolean verify(
final char[]
password,
final byte[] salt,
final int iterations,
final byte[] expectedHash) {
67 if (
password ==
null || salt ==
null || expectedHash ==
null || iterations <= 0) {
71 final var derivedKey = derive(
password, salt, iterations, expectedHash.length);
73 return MessageDigest.isEqual(derivedKey, expectedHash);
75 Arrays.fill(derivedKey, (
byte) 0);
91 throw new IllegalArgumentException(
"password no puede ser null");
93 if (salt ==
null || salt.length == 0) {
94 throw new IllegalArgumentException(
"salt no puede ser null o vacio");
96 if (iterations <= 0) {
97 throw new IllegalArgumentException(
"iterations debe ser mayor que cero");
100 final var derivedKey = derive(
password, salt, iterations, derivedKeyBytes);
104 private static byte[] derive(
final char[]
password,
final byte[] salt,
final int iterations,
105 final int outLenBytes) {
107 final var spec =
new PBEKeySpec(
password, salt, iterations, outLenBytes * 8);
108 final var secretKeyFactory = SecretKeyFactory.getInstance(ALGORITHM);
109 return secretKeyFactory.generateSecret(spec).getEncoded();
110 }
catch (
final Exception e) {
111 throw new IllegalStateException(
"PBKDF2 derivation failed", e);
boolean verify(final char[] password, final byte[] salt, final int iterations, final byte[] expectedHash)
Verifies a password against an expected hash using PBKDF2-HMAC-SHA256.
PasswordHasherPBKDF2(final int derivedKeyBytes)
Creates a new PBKDF2 password hasher.
PasswordHash hash(final char[] password, final byte[] salt, final int iterations)
Hashes a password using PBKDF2-HMAC-SHA256.
Contract for password hashing and verification.
Password hashing and verification primitives for Ether.
record PasswordHash(byte[] hash, byte[] salt, int iterations)
Immutable password hash material.