PBKDF2,PBKDF2简单而言就是将salted hash进行多次重复计算,这个次数是可选择的。如果计算一次所需要的时间是1微秒,那么计算1百万次就需要1秒钟。假如攻击一个密码所需的rainbow table有1千万条,建立所对应的rainbow table所需要的时间就是115天。这个代价足以让大部分的攻击者望而生畏。
/**
* 密码加密
* @param password
* @param salt
* @return
*/
public static String getPBKDF2(String password, String salt) {
//将16进制字符串形式的salt转换成byte数组
byte[] bytes = java.util.Base64.getDecoder().decode(salt);
KeySpec spec = new PBEKeySpec(password.toCharArray(), bytes, 10000, 256);
SecretKeyFactory secretKeyFactory = null;
try { //PBKDF2WithHmacSHA1 PBKDF2WithHmacSHA256
secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] hash = new byte[0];
try {
hash = secretKeyFactory.generateSecret(spec).getEncoded();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
//将byte数组转换为16进制的字符串
return java.util.Base64.getEncoder().encodeToString(hash);
}
/**
* 获取盐值
* @return
*/
public static String salt() {
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[16];
random.nextBytes(bytes);
String s = java.util.Base64.getEncoder().encodeToString(bytes);
return s;
}