I'm using pbkdf2 to hash my passwords. I take a plain string password, I generate a salt, and I hash it like this:
byte[] salt = SecureRandom.getSeed(16);
KeySpec spec = new PBEKeySpec(
password.toCharArray(),
salt,
iterations,
keyLength * 8
);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] generatedSecret = f.generateSecret(spec).getEncoded();
Then I save the salt (BINARY(64)
) and the hashed password (BINARY(255)
) inside my MySQL table using prepared statement SELECT
.
When I try to validate a user, I first fetch the salt, with it I generate the password hash and I use it inside the SELECT
query for the user.
The salt gets fetched correctly and is the same every time, but the generated hash is always different.
I reproduced it here
Edit: in the link above the error is indeed the fact that I have to use Arrays.equals(a, b)
to compare two byte[]
.