/** * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @return a salted PBKDF2 hash of the password */ public String createHash(final char[] password) { // Generate a random salt SecureRandom random = new SecureRandom(); byte[] salt = new byte[saltBytes]; random.nextBytes(salt); // Hash the password byte[] hash = pbkdf2(password, salt, pbkdf2Iterations, hashBytes); // format iterations:salt:hash return pbkdf2Iterations + ":" + StringUtil.toHexString(salt) + ":" + StringUtil.toHexString(hash); }
/** * Validates a password using a hash. * * @param password the password to check * @param goodHash the hash of the valid password * @return true if the password is correct, false if not */ public boolean validatePassword(final char[] password, final String goodHash) { // Decode the hash into its parameters String[] params = goodHash.split(":"); int iterations = Integer.parseInt(params[ITERATION_INDEX]); byte[] salt = fromHex(params[SALT_INDEX]); byte[] hash = fromHex(params[PBKDF2_INDEX]); // Compute the hash of the provided password, using the same salt, // iteration count, and hash length byte[] testHash = pbkdf2(password, salt, iterations, hash.length); // Compare the hashes in constant time. The password is correct if // both hashes match. return slowEquals(hash, testHash); }
/** * Returns a salted PBKDF2 hash of the password. * * @param password the password to hash * @return a salted PBKDF2 hash of the password */ public String createHash(final char[] password) { // Generate a random salt SecureRandom random = new SecureRandom(); byte[] salt = new byte[saltBytes]; random.nextBytes(salt); // Hash the password byte[] hash = pbkdf2(password, salt, pbkdf2Iterations, hashBytes); // format iterations:salt:hash return pbkdf2Iterations + ":" + StringUtil.toHexString(salt) + ":" + StringUtil.toHexString(hash); }
/** * Validates a password using a hash. * * @param password the password to check * @param goodHash the hash of the valid password * @return true if the password is correct, false if not */ public boolean validatePassword(final char[] password, final String goodHash) { // Decode the hash into its parameters String[] params = goodHash.split(":"); int iterations = Integer.parseInt(params[ITERATION_INDEX]); byte[] salt = fromHex(params[SALT_INDEX]); byte[] hash = fromHex(params[PBKDF2_INDEX]); // Compute the hash of the provided password, using the same salt, // iteration count, and hash length byte[] testHash = pbkdf2(password, salt, iterations, hash.length); // Compare the hashes in constant time. The password is correct if // both hashes match. return slowEquals(hash, testHash); }