213 shaares
1 résultat
taggé
password
I have no idea what I am doing...
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
public class Authentication {
private static Logger LOGGER = LoggerFactory.getLogger(Authentication.class.getCanonicalName());
// Are these sizes arbitrary ?
private static final int SEED_BYTES = 20;
private static final int HASH_BYTES = 20;
// increase iterations as high as your performance can tolerate
// since this increases computational cost of password guessing
// which should help security
private static final int ITERATIONS = 1000;
//Encoding
public static final String ENCODING = "UTF-8";
public String generateSalt() {
return new String(new SecureRandom().generateSeed(SEED_BYTES));
}
public String hashToken(String password, String salt) {
try {
PKCS5S2ParametersGenerator kdf = new PKCS5S2ParametersGenerator();
kdf.init(password.getBytes(ENCODING), salt.getBytes(ENCODING), ITERATIONS);
return new String(((KeyParameter) kdf.generateDerivedMacParameters(8 * HASH_BYTES)).getKey());
} catch (UnsupportedEncodingException exception) {
LOGGER.info("Error when hashing password : {}", exception.getMessage());
}
return null;
}
public boolean isPasswordValid(String givenPassword, String salt, String storedHash) {
return this.hashToken(givenPassword, salt).equals(storedHash);
}
}