/**
* <p> From a password, a number of iterations and a salt, returns the corresponding hash. </p> <p> If the salt is to be appended, this convention is used: <code>base64(hash(plainTextValue + salt)+salt)</code> </p> <p> If the salt is NOT to be appended, this convention is used: <code>base64(hash(plainTextValue + salt))</code> </p>
* @param plainTextValue String The password to encrypt
* @param salt byte[] The salt. If null, one will be created on your behalf.
* @param appendSalt True if the salt is to be appended to hashed value. In this way, for convenience, the salt can be kept with the hash. Use this only if the hash is to be kept internal to this app. If the hash is to be sent to external systems, set this to false and store the hash internally.
* @return String The hash password
* @throws ChiliLogException if SHA-512 is not supported or UTF-8 is not a supported encoding algorithm
*/
public static String createSHA512Hash(String plainTextValue,byte[] salt,boolean appendSalt) throws ChiliLogException {
try {
if (plainTextValue == null) {
throw new NullArgumentException("plainTextValue");
}
if (salt == null) {
throw new NullArgumentException("salt");
}
byte[] plainTextBytes=plainTextValue.getBytes("UTF-8");
byte[] plainTextWithSaltBytes=new byte[plainTextBytes.length + salt.length];
for (int i=0; i < plainTextBytes.length; i++) {
plainTextWithSaltBytes[i]=plainTextBytes[i];
}
if (appendSalt) {
for (int i=0; i < salt.length; i++) {
plainTextWithSaltBytes[plainTextBytes.length + i]=salt[i];
}
}
MessageDigest digest=MessageDigest.getInstance("SHA-512");
digest.reset();
byte[] hashBytes=digest.digest(plainTextWithSaltBytes);
byte[] hashWithSaltBytes=new byte[hashBytes.length + salt.length];
for (int i=0; i < hashBytes.length; i++) {
hashWithSaltBytes[i]=hashBytes[i];
}
for (int i=0; i < salt.length; i++) {
hashWithSaltBytes[hashBytes.length + i]=salt[i];
}
Base64 encoder=new Base64(1000,new byte[]{},false);
return encoder.encodeToString(hashWithSaltBytes);
}
catch ( Exception ex) {
throw new ChiliLogException(ex,"Error attempting to hash passwords. " + ex.getMessage());
}
}

Example 6

From project collector, under directory /src/test/java/com/ning/metrics/collector/.