Skip to content

Instantly share code, notes, and snippets.

@gembin
Forked from craSH/pbkdf2.java
Created October 8, 2012 07:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gembin/3851131 to your computer and use it in GitHub Desktop.
Save gembin/3851131 to your computer and use it in GitHub Desktop.
Java PBKDF2 method + string wrapper, relies on some external methods for converting to hex strings.
public String hashPassword(String password, String salt) throws Exception
/*
* Wrap pbkdf2 method to return password hash as a hex string
*/
{
// Bail if password or salt are null/0 length
if ((null == password || 0 == password.length()) || (null == salt || 0 == salt.length()))
throw new Exception("Failed to create PBKDF2 Hash for password, password or salt can not be empty");
// Result string
String hash = null;
hash = convertBytesToHexString(pbkdf2(password, salt));
// Ensure that the hashing didn't fail
if (null != hash && hash.length() > 0)
return hash;
else
throw new Exception("Failed to create PBKDF2 Hash for password");
}
public byte[] pbkdf2(String password, String salt) throws Exception
{
// Bail if password or salt are null/0 length
if ((null == password || 0 == password.length()) || (null == salt || 0 == salt.length())) return null;
// Convert password and salt to character array/byte array
char[] password_char = password.toCharArray();
byte[] salt_bytes = salt.getBytes();
// Define number of iterations and output size
int iterations = 5000;
int result_size = 256;
// The result - null if any failure
byte[] pbkdf2_result = null;
try {
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
// PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength)
PBEKeySpec ks = new PBEKeySpec(password_char, salt_bytes, iterations, result_size);
// Generate the password hash
SecretKey s = skf.generateSecret(ks);
// Immediately zero the password from memory
ks.clearPassword();
// Get the resulting byte array of our PBKDF2 hash
pbkdf2_result = s.getEncoded();
}
catch (Exception e)
{
throw e;
}
return pbkdf2_result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment