private static byte[] normalizeKeyForHMAC(byte[] key) { if (key.length > 64) { key = getHash(key, false); } if (key.length < 64) { key = Arrays.copyOf(key, 64); } return key; }
/** * Calculate the hash code by using the given salt. The salt is appended * after the data before the hash code is calculated. After generating the * hash code, the data and all internal buffers are filled with zeros to avoid * keeping insecure data in memory longer than required (and possibly * swapped to disk). * * @param data the data to hash * @param salt the salt to use * @return the hash code */ public static byte[] getHashWithSalt(byte[] data, byte[] salt) { byte[] buff = new byte[data.length + salt.length]; System.arraycopy(data, 0, buff, 0, data.length); System.arraycopy(salt, 0, buff, data.length, salt.length); return getHash(buff, true); }
private static byte[] getHash(String algorithm, byte[] bytes, int iterations) { if (!"SHA256".equalsIgnoreCase(algorithm)) { throw DbException.getInvalidValueException("algorithm", algorithm); } for (int i = 0; i < iterations; i++) { bytes = SHA256.getHash(bytes, false); } return bytes; }
/** * Calculate the hash of a password by prepending the user name and a '@' * character. Both the user name and the password are encoded to a byte * array using UTF-16. After generating the hash code, the password array * and all internal buffers are filled with zeros to avoid keeping the plain text * password in memory longer than required (and possibly swapped to disk). * * @param userName the user name * @param password the password * @return the hash code */ public static byte[] getKeyPasswordHash(String userName, char[] password) { String user = userName + "@"; byte[] buff = new byte[2 * (user.length() + password.length)]; int n = 0; for (int i = 0, length = user.length(); i < length; i++) { char c = user.charAt(i); buff[n++] = (byte) (c >> 8); buff[n++] = (byte) c; } for (char c : password) { buff[n++] = (byte) (c >> 8); buff[n++] = (byte) c; } Arrays.fill(password, (char) 0); return getHash(buff, true); }