-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPBKDF2Hashing.java
39 lines (28 loc) · 1.31 KB
/
PBKDF2Hashing.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.wtech.core.hashing;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.Base64;
public class PBKDF2Hashing {
public static String hashPassword(String password) throws Exception {
// Securely generate a random salt
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return hashPasswordWithSalt(password, salt);
}
public static String hashPasswordWithSalt(String password, byte[] salt) throws Exception {
// Set realistic values for parameters
int iterationCount = 65536; // How many iterations to use
int keyLength = 256; // Derived key length
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
byte[] hash = factory.generateSecret(spec).getEncoded();
return Base64.getEncoder().encodeToString(hash);
}
public static boolean verifyPassword(String inputPassword, String storedHash, byte[] salt) throws Exception {
String newHash = hashPasswordWithSalt(inputPassword, salt);
return newHash.equals(storedHash);
}
}