原理底层啥的就不说了,小白的我只注重使用
SHA-2加密
// 生成随机盐
public static String generateSalt() {
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
return Base64.getEncoder().encodeToString(salt);
}
// 哈希密码
public static String hashPassword(String password, String salt) throws NoSuchAlgorithmException {
String saltedPassword = new StringBuffer(salt).append(password).toString();
// 这里可以使用SHA-224,SHA-256,SHA-384,SHA-512, 只是生成消息摘要长度,循环次数不同之外,算法基本一致
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashedPassword = md.digest(saltedPassword.getBytes());
return Base64.getEncoder().encodeToString(hashedPassword);
}
// 验证密码
public static boolean verifyPassword(String password, String salt, String hashedPassword) throws NoSuchAlgorithmException {
String hashedInput = hashPassword(password, salt);
return hashedInput.equals(hashedPassword);
}
public static void main(String[] args) throws NoSuchAlgorithmException {
// 示例演示了密码哈希和加盐存储的过程
String password = "myPassword123";
String salt = generateSalt();
String hashedPassword = hashPassword(password, salt);
System.out.println("原密码: " + password);
System.out.println("盐: " + salt);
System.out.println("哈希后的密码: " + hashedPassword);
// 验证密码
boolean isValid = verifyPassword(password, salt, hashedPassword);
System.out.println("密码验证结果: " + isValid);
}
springboot-bcrypt加密
引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
使用
public static void main(String[] args) {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
// 加密。不需要加盐,它内部已经加盐了
System.out.println(bCryptPasswordEncoder.encode("123456"));
// 比对
System.out.println(bCryptPasswordEncoder.matches("123456", "$2a$10$THlC1Z46enO4b6bjqMIQjug9ip9YFDROuCHLPOppMllgz1X3dCZ8a"));
}