org.cinchapi.runway.util.Secrets Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of runway Show documentation
Show all versions of runway Show documentation
The official ORM (Object-Record Mapping) framework for Concourse
package org.cinchapi.runway.util;
import java.security.SecureRandom;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.BaseEncoding;
/**
* Contains security related utility functions for dealing with sensitive data
* (i.e. password hashing).
*
* @author jnelson
*/
public final class Secrets {
/**
* Given the {@code email}/{@code password} combination, return the expected
* password hash if the data is salted with {@code salt} for the specified
* number of {@code rounds}.
*
* @param email
* @param password
* @param salt
* @param rounds
* @return the expected password hash
*/
public static String getExpectedPasswordHash(String email, String password,
String salt, int rounds) {
return hash(email + password + email, salt, rounds);
}
/**
* Return a 64-bit (128 character long) string that represents a hash of
* {@code data} salted with {@code salt} for the specified number of
* {@code rounds}. The hash that is returned cannot be "unhashed" back to
* the original data.
*
* @param data
* @param salt
* @param rounds
* @return the hash
*/
public static String hash(String data, String salt, int rounds) {
Preconditions.checkArgument(!salt.isEmpty());
Preconditions.checkArgument(rounds > 0);
// The actual salt that is used in the hashing scheme is generated by
// SHA-256 hashing the initial salt for a certain number of rounds.
// During each round, we Base64 encode the salt before hashing to ensure
// that we don't reduce our hash alphabet.
for (int i = 0; i < rounds; i++) {
salt = BaseEncoding.base64().encode(
Hashing.sha256().hashUnencodedChars(salt).asBytes());
}
return Hashing.sha512().hashUnencodedChars(data + salt).toString();
}
/**
* The provider of all secure randomness.
*/
public static final SecureRandom SRAND = new SecureRandom();
private Secrets() {/* noop */}
}