Reputation: 31
i'm trying to write a sign in activity , i wrote the hashPassword
function below. Why does it give a different result for the same salt and password?
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
public class Main {
public static void main(String[] args) {
System.out.println("Hello World!");
try { System.out.println("test1: "+hashPassword("[B@2b1e4124","bfnfnfjfjf"));
System.out.println("test2: "+hashPassword("[B@2b1e4124","bfnfnfjfjf"));}
catch (NoSuchAlgorithmException | InvalidKeySpecException e){}
}
public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
char[] passwordChars = password.toCharArray();
byte[] saltBytes =salt.getBytes();
PBEKeySpec spec = new PBEKeySpec(
passwordChars,
saltBytes,
5000,
10
);
SecretKeyFactory key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
byte[] hashedPassword = key.generateSecret(spec).getEncoded();
return hashedPassword.toString();
}
}
Upvotes: 3
Views: 93
Reputation: 7286
Your hash is actually calculating the same result each time, but you're calling toString
on the resulting byte array. This returns a debug string, which is different for each instance (see this question for details).
Instead of
return hashedPassword.toString();
You should
return hashedPassword;
... and use the byte[]
directly.
If you want to display the hash in a human readable format, you could print it like this:
String hashString = new BigInteger(1, hashedPassword).toString(16);
System.out.println(hashString);
There is a second mistake in your code. The forth argument to the PBEKeySpec
constructor is the length in bits. 10 is way too short to be useful. You probably want 512 (the SHA512 output length).
Upvotes: 1