-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathPBKDF2.java
41 lines (34 loc) · 1.37 KB
/
PBKDF2.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
39
40
41
package cryptography.hashes.pbkdf2;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class PBKDF2 {
public static void main(String[] args) {
}
public static String createHash(
PBKDF2HmacOption hmacAlgorithm, String password, String salt, int iterations, int dkLen
) throws NoSuchAlgorithmException, InvalidKeySpecException {
byte[] saltBytes = salt.getBytes(StandardCharsets.UTF_8);
byte[] hash = pbkdf2(hmacAlgorithm, password.toCharArray(), saltBytes, iterations, dkLen);
return toHex(hash);
}
private static byte[] pbkdf2(
PBKDF2HmacOption hmacAlgorithm, char[] password, byte[] salt, int iterations, int bits
) throws NoSuchAlgorithmException, InvalidKeySpecException {
PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bits);
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2With" + hmacAlgorithm.name());
return skf.generateSecret(spec).getEncoded();
}
private static String toHex(byte[] array) {
BigInteger bi = new BigInteger(1, array);
String hex = bi.toString(16);
int paddingLength = (array.length * 2) - hex.length();
if (paddingLength > 0)
return String.format("%0" + paddingLength + "d", 0) + hex;
else
return hex;
}
}