1.BCrypt的概述
bcrypt 是一种密码哈希函数,通常用于加密密码。它采用了 Blowfish 加密算法的变种,并结合了盐(salt)和密钥延时(key stretching)等技术,以增加密码破解的难度。
2.BCrypt的使用
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
添加安全配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;/*** @author : luobei* @date : 2024/4/15 8:34*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {protected void configure(HttpSecurity http) throws Exception{http.authorizeRequests()//定义要控制的路径为所有.antMatchers("/**")//允许所有人访问上述路径.permitAll()//关闭csrf保护(跨域问题).and().csrf().disable();super.configure(http);}@Beanpublic BCryptPasswordEncoder bCryptPasswordEncoder(){return new BCryptPasswordEncoder();}
}
使用BCrypt加密
@Autowiredprivate BCryptPasswordEncoder bCryptPasswordEncoder;@PostMapping("/registration")public Object registration(User user){user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));return userService.addUser(user);}