加密与密码匹配
(1)加密:注册用户时,使用SHA-256+随机盐+密钥把用户输入的密码进行hash处理,得到密码的hash值,然后将其存入数据库中。
(2)密码匹配:用户登录时,密码匹配阶段并没有进行密码解密(因为密码经过Hash处理,是不可逆的),而是使用相同的算法把用户输入的密码进行hash处理,得到密码的hash值,然后将其与从数据库中查询到的密码hash值进行比较。如果两者相同,说明用户输入的密码正确。
依赖
<!-- spring security 安全认证 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
代码实现
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class SecurityUtils {
/**
* 加密
*
* @param password 密码
* @return 加密字符串
*/
public static String encryptPassword(String password) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
/**
* 密码匹配
*
* @param realPassword 真实密码
* @param encodedPassword 加密后字符
* @return true(密码正确) false(密码错误)
*/
public static boolean matchesPassword(String realPassword, String encodedPassword) {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(realPassword, encodedPassword);
}
}
测试
public static void main(String[] args) {
String password = "admin";
String hashPassword = encryptPassword(password);
System.out.println(hashPassword);
boolean b = matchesPassword("admin",hashPassword);
System.out.println(b? "密码正确": "密码错误");
}