private byte[] getPbkdf2(final String iPassword, final byte[] salt, final int iterations, final int bytes, final String algorithm) { String cacheKey = null; final String hashedPassword = createSHA256(iPassword + new String(salt)); if (SALT_CACHE != null) { // SEARCH IN CACHE FIRST cacheKey = hashedPassword + "|" + Arrays.toString(salt) + "|" + iterations + "|" + bytes; final byte[] encoded = SALT_CACHE.get(cacheKey); if (encoded != null) return encoded; } final PBEKeySpec spec = new PBEKeySpec(iPassword.toCharArray(), salt, iterations, bytes * 8); final SecretKeyFactory skf; try { skf = SecretKeyFactory.getInstance(algorithm); final byte[] encoded = skf.generateSecret(spec).getEncoded(); if (SALT_CACHE != null) { // SAVE IT IN CACHE SALT_CACHE.put(cacheKey, encoded); } return encoded; } catch (Exception e) { throw OException.wrapException(new OSecurityException("Cannot create a key with '" + algorithm + "' algorithm"), e); } }
/** * Checks if an hash string matches a password, based on the algorithm found on hash string. * * @param iHash * Hash string. Can contain the algorithm as prefix in the format <code>{ALGORITHM}-HASH</code>. * @param iPassword * @return */ public boolean checkPassword(final String iPassword, final String iHash) { if (iHash.startsWith(HASH_ALGORITHM_PREFIX)) { final String s = iHash.substring(HASH_ALGORITHM_PREFIX.length()); return createSHA256(iPassword).equals(s); } else if (iHash.startsWith(PBKDF2_ALGORITHM_PREFIX)) { final String s = iHash.substring(PBKDF2_ALGORITHM_PREFIX.length()); return checkPasswordWithSalt(iPassword, s, PBKDF2_ALGORITHM); } else if (iHash.startsWith(PBKDF2_SHA256_ALGORITHM_PREFIX)) { final String s = iHash.substring(PBKDF2_SHA256_ALGORITHM_PREFIX.length()); return checkPasswordWithSalt(iPassword, s, PBKDF2_SHA256_ALGORITHM); } // Do not compare raw strings against each other, to avoid timing attacks. // Instead, hash them both with a cryptographic hash function and // compare their hashes with a constant-time comparison method. return MessageDigest.isEqual(digestSHA256(iPassword), digestSHA256(iHash)); }
transformed = createSHA256(iInput); } else if (PBKDF2_ALGORITHM.equalsIgnoreCase(algorithm)) { transformed = createHashWithSalt(iInput, OGlobalConfiguration.SECURITY_USER_PASSWORD_SALT_ITERATIONS.getValueAsInteger(),