1. 添加依赖:
在pom.xml文件中添加Spring Security依赖,以使用BCryptPasswordEncoder。
<!-- Spring Security 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. 配置BCryptPasswordEncoder Bean:
创建一个配置类,配置一个BCryptPasswordEncoder Bean
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
3. 在服务类中注入PasswordEncoder:
在需要对密码进行加密的地方,使用@Autowired注解注入PasswordEncoder接口。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private PasswordEncoder passwordEncoder;
public void registerUser(String username, String rawPassword) {
String encodedPassword = passwordEncoder.encode(rawPassword);
// 将encodedPassword存储到数据库
}
}
4. 存储加密后的密码:
将加密后的密码存储到MySQL数据库中。建议使用VARCHAR(255)
类型的列来存储BCrypt哈希值,因为BCrypt哈希不会超过70个字符
。
5. 验证密码:
当用户登录时,使用matches方法来验证用户输入的密码是否与数据库中存储的加密密码匹配。
public boolean checkPassword(String rawPassword, String encodedPassword) {
return passwordEncoder.matches(rawPassword, encodedPassword);
}
6. 关于BCrypt:
- BCrypt 是一种基于Blowfish密码算法的密码哈希函数,专门设计用于密码存储。它通过使用盐值(salt)和多次迭代来增加密码破解的难度。
- BCrypt 自动为每个密码生成一个随机的盐值,并且将盐值和密码一起进行哈希,这样即使两个用户有相同的密码,他们的哈希值也会不同。