
在现代应用中,直接存储用户密码是极度不安全的做法。密码哈希是将密码转换为固定长度的不可逆字符串的过程。pbkdf2(password-based key derivation function 2)是一种推荐的密钥派生函数,用于安全地存储密码。它通过多次迭代(即“拉伸”)和使用随机生成的盐值(salt)来增加计算哈希的成本,从而有效抵御暴力破解和彩虹表攻击。
盐值(Salt)的作用: 盐值是一个随机生成的数据,与密码一同参与哈希计算。每个用户的密码都应使用一个唯一的盐值。这样即使两个用户设置了相同的密码,其哈希值也会不同,极大地增强了安全性。盐值不需要保密,但必须与哈希值一同存储,以便在验证时使用。
生成密码哈希是存储用户密码的第一步。此过程涉及生成一个随机盐值,然后使用PBKDF2算法将密码与盐值结合进行哈希。
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64; // 用于将字节数组转换为字符串以便存储和显示
public class PasswordHasher {
// 定义PBKDF2算法的参数
private static final String ALGORITHM = "PBKDF2WithHmacSHA1"; // 算法名称
private static final int ITERATIONS = 65536; // 迭代次数,应足够高以增加计算成本
private static final int KEY_LENGTH = 128; // 密钥长度(位),通常为128位或256位
private static final int SALT_LENGTH = 16; // 盐值长度(字节)
/**
* 生成密码的哈希值和对应的盐值。
*
* @param password 待哈希的原始密码
* @return 包含哈希值和盐值的PasswordHashResult对象
* @throws NoSuchAlgorithmException 如果PBKDF2WithHmacSHA1算法不可用
* @throws InvalidKeySpecException 如果PBEKeySpec规范无效
*/
public PasswordHashResult generateHash(String password)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[SALT_LENGTH];
random.nextBytes(salt); // 生成随机盐值
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, ITERATIONS, KEY_LENGTH);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
byte[] hash = factory.generateSecret(spec).getEncoded();
// 返回哈希值和盐值,通常需要将它们转换为字符串(如Base64)以便存储
return new PasswordHashResult(Base64.getEncoder().encodeToString(hash),
Base64.getEncoder().encodeToString(salt));
}
/**
* 用于存储哈希值和盐值的简单数据结构。
*/
public static class PasswordHashResult {
private final String hashedPassword;
private final String salt;
public PasswordHashResult(String hashedPassword, String salt) {
this.hashedPassword = hashedPassword;
this.salt = salt;
}
public String getHashedPassword() {
return hashedPassword;
}
public String getSalt() {
return salt;
}
}
// 示例用法:
public static void main(String[] args) {
PasswordHasher hasher = new PasswordHasher();
try {
String userPassword = "MySecurePassword123";
PasswordHashResult result = hasher.generateHash(userPassword);
System.out.println("原始密码: " + userPassword);
System.out.println("生成的哈希: " + result.getHashedPassword());
System.out.println("对应的盐值: " + result.getSalt());
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
}
}注意事项:
密码验证的关键在于:你不能从哈希值中恢复原始密码。 相反,当用户尝试登录时,你需要做的是:
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.MessageDigest; // 用于安全地比较字节数组
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
public class PasswordVerifier {
private static final String ALGORITHM = "PBKDF2WithHmacSHA1";
private static final int ITERATIONS = 65536;
private static final int KEY_LENGTH = 128;
/**
* 验证用户输入的密码是否与存储的哈希值匹配。
*
* @param inputPassword 用户在登录时输入的密码
* @param storedHashedPassword 从数据库中获取的已哈希密码(Base64编码)
* @param storedSalt 从数据库中获取的盐值(Base64编码)
* @return 如果密码匹配返回true,否则返回false
* @throws NoSuchAlgorithmException 如果PBKDF2WithHmacSHA1算法不可用
* @throws InvalidKeySpecException 如果PBEKeySpec规范无效
*/
public boolean verifyPassword(String inputPassword, String storedHashedPassword, String storedSalt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// 将Base64编码的哈希值和盐值解码回字节数组
byte[] saltBytes = Base64.getDecoder().decode(storedSalt);
byte[] storedHashBytes = Base64.getDecoder().decode(storedHashedPassword);
// 使用用户输入的密码和存储的盐值重新计算哈希值
KeySpec spec = new PBEKeySpec(inputPassword.toCharArray(), saltBytes, ITERATIONS, KEY_LENGTH);
SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
byte[] inputHashBytes = factory.generateSecret(spec).getEncoded();
// 使用MessageDigest.isEqual()进行常量时间比较,防止时序攻击
return MessageDigest.isEqual(inputHashBytes, storedHashBytes);
}
// 示例用法:
public static void main(String[] args) {
PasswordHasher hasher = new PasswordHasher();
PasswordVerifier verifier = new PasswordVerifier();
try {
String userPassword = "MySecurePassword123";
// 1. 生成并存储哈希和盐值(模拟注册过程)
PasswordHasher.PasswordHashResult storedResult = hasher.generateHash(userPassword);
String storedHashedPassword = storedResult.getHashedPassword();
String storedSalt = storedResult.getSalt();
System.out.println("--- 模拟存储 ---");
System.out.println("存储的哈希: " + storedHashedPassword);
System.out.println("存储的盐值: " + storedSalt);
System.out.println("----------------\n");
// 2. 验证正确的密码
String loginAttempt1 = "MySecurePassword123";
boolean isCorrect = verifier.verifyPassword(loginAttempt1, storedHashedPassword, storedSalt);
System.out.println("尝试登录密码: '" + loginAttempt1 + "' -> 验证结果: " + (isCorrect ? "成功" : "失败"));
// 3. 验证错误的密码
String loginAttempt2 = "WrongPassword";
boolean isWrong = verifier.verifyPassword(loginAttempt2, storedHashedPassword, storedSalt);
System.out.println("尝试登录密码: '" + loginAttempt2 + "' -> 验证结果: " + (isWrong ? "成功" : "失败"));
// 4. 验证大小写不同的密码(通常被视为不同密码)
String loginAttempt3 = "mysecurepassword123";
boolean isCaseDiff = verifier.verifyPassword(loginAttempt3, storedHashedPassword, storedSalt);
System.out.println("尝试登录密码: '" + loginAttempt3 + "' -> 验证结果: " + (isCaseDiff ? "成功" : "失败"));
} catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
e.printStackTrace();
}
}
}关键点:
立即学习“Java免费学习笔记(深入)”;
通过上述方法,我们实现了基于PBKDF2算法的Java密码哈希生成与验证机制。这种方法提供了强大的安全性,有效保护用户密码免受常见攻击。
额外建议和最佳实践:
以上就是Java中PBKDF2密码哈希的生成与验证的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号