· 7 years ago · Oct 21, 2018, 04:38 AM
1public String hashPassword(String password, String salt) throws Exception
2/*
3 * Wrap pbkdf2 method to return password hash as a hex string
4*/
5{
6 // Bail if password or salt are null/0 length
7 if ((null == password || 0 == password.length()) || (null == salt || 0 == salt.length()))
8 throw new Exception("Failed to create PBKDF2 Hash for password, password or salt can not be empty");
9
10 // Result string
11 String hash = null;
12
13 hash = convertBytesToHexString(pbkdf2(password, salt));
14
15 // Ensure that the hashing didn't fail
16 if (null != hash && hash.length() > 0)
17 return hash;
18 else
19 throw new Exception("Failed to create PBKDF2 Hash for password");
20}
21
22public byte[] pbkdf2(String password, String salt) throws Exception
23{
24 // Bail if password or salt are null/0 length
25 if ((null == password || 0 == password.length()) || (null == salt || 0 == salt.length())) return null;
26
27 // Convert password and salt to character array/byte array
28 char[] password_char = password.toCharArray();
29 byte[] salt_bytes = salt.getBytes();
30
31 // Define number of iterations and output size
32 int iterations = 5000;
33 int result_size = 256;
34
35 // The result - null if any failure
36 byte[] pbkdf2_result = null;
37
38 try {
39 SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
40
41 // PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)
42 PBEKeySpec ks = new PBEKeySpec(password_char, salt_bytes, iterations, result_size);
43
44 // Generate the password hash
45 SecretKey s = skf.generateSecret(ks);
46
47 // Immediately zero the password from memory
48 ks.clearPassword();
49
50 // Get the resulting byte array of our PBKDF2 hash
51 pbkdf2_result = s.getEncoded();
52 }
53 catch (Exception e)
54 {
55 throw e;
56 }
57
58 return pbkdf2_result;
59}