@SpringBootTest
class ApplicationTests {
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Test
public void testBCryptPasswordEncoder() {
for (int i = 0; i < 10; i++) {
String password = "123456";
String hashed = bCryptPasswordEncoder.encode(password);
System.out.println(hashed);
}
}
}
加密后的密码长度为60(所以设计数据库时得保证该字段长度不小于60)
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and().csrf().disable();
}
}
(三)启动类中配置bean
@Bean
public BCryptPasswordEncoder getBcryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
(四)加密密码
// 加密密码
user.setPassword(bCryptPasswordEncoder.encode(password));
五)校验密码
// 参数一:待检验的、未加密的密码
// 参数二:从数据库中查询出的加密后密码
bCryptPasswordEncoder.matches(password, userFromDB.getPassword())