SpringBoot中使用Hash
1. 添加 Spring Security 依赖
如果项目没有 Spring Security:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. 创建 PasswordEncoder
Spring Security 提供了:
BCryptPasswordEncoder
在config目录中创建PasswordConfig.java
@Configuration
public class PasswordConfig {
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
之后 Spring 会自动管理这个 Bean。
3. 注册时加密密码
例如你的用户注册:
@Service
public class UserService {
// 注入配置类
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserAuthMapper userAuthMapper;
public void register(UserAuth user){
// 明文密码
String rawPassword = user.getPassword();
// 加密
String encodePassword =
passwordEncoder.encode(rawPassword);
// 替换为密文
user.setPassword(encodePassword);
// 存入数据库
userAuthMapper.insert(user);
}
}
假设用户输入:
123456
数据库保存:
$2a$10$8JjKp7VZxq7mXyqz9qzDNe8....
而不是:
123456
4. 登录时验证密码
不要这样:
if(user.getPassword().equals(inputPassword)){
}
因为数据库里已经不是明文。
应该:
boolean result =
passwordEncoder.matches(
inputPassword,
user.getPassword()
);
if(result){
// 登录成功
}
例如:
数据库:
password:
$2a$10$8JjKp7VZxq7mXyqz9qzDNe8....
用户输入:
123456
执行:
passwordEncoder.matches(
"123456",
"$2a$10$8JjKp7..."
)
返回:
true

浙公网安备 33010602011771号