1、generateSalt()获取16字节的加密盐
2、hashPassword(String password, String salt) 使用 SHA-256 算法加盐计算哈希值
3、verifyPassword(String inputPassword, String storedHash, String storedSalt)验证密码是否正确
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class Sha256Utils {
public static String generateSalt() {
SecureRandom secureRandom = new SecureRandom();
byte[] salt = new byte[16]; // 16字节盐值
secureRandom.nextBytes(salt);
return Base64.getEncoder().encodeToString(salt); // 返回盐值的Base64编码字符串
}
// 使用 SHA-256 算法加盐计算哈希值
public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException {
// 拼接密码和盐值
String passwordWithSalt = password + salt;
// 使用 SHA-256 计算哈希值
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashedBytes = digest.digest(passwordWithSalt.getBytes());
// 返回计算得到的哈希值的Base64编码字符串
return Base64.getEncoder().encodeToString(hashedBytes);
}
// 验证密码是否正确
public static boolean verifyPassword(String inputPassword, String storedHash, String storedSalt) throws NoSuchAlgorithmException {
// 使用相同的盐值计算输入密码的哈希值
String hashOfInput = hashPassword(inputPassword, storedSalt);
// 比较计算出的哈希值与存储的哈希值
return hashOfInput.equals(storedHash);
}
public static void main(String[] args) throws NoSuchAlgorithmException {
// 模拟用户注册
String password = "password";
// 生成盐值
String salt = generateSalt();
System.out.println("Salt: " + salt);
// 计算密码的哈希值
String hash = hashPassword(password, salt);
System.out.println("Password Hash: " + hash);
// 模拟用户登录验证
String inputPassword = "password"; // 用户输入的密码
boolean isPasswordCorrect = verifyPassword(inputPassword, hash, salt);
System.out.println("Password verification result: " + isPasswordCorrect);
}
}