版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wangb_java/article/details/86676166
从spring security5开始,要求必须手动配置密码加密方式,spring官方推荐使用BCrypt加密,并明确指出sha和md5都是不安全的。本篇仅介绍BCrypt的用法。
BCrypt加密与验证
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String result = encoder.encode("123"); //注册时,对密码123加密,结果将保存到数据库
encoder.matches("123", result); //登录时,从数据库读取密文,验证密码是否是123
基本配置
password方法参数就是上面加密过result,此时在登录界面输入密码123,将使用上面的matches方法验证密码。
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("$2a$10$89rbg/..2V1hoRzXtlDa9ejjIzsqeO.kQgmkQnAa//xDzJLoyJgAu").authorities("auth")
.and()
.passwordEncoder(new BCryptPasswordEncoder());//配置BCrypt加密
}
passwordEncoder配置也可以换成以下方式
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
兼容多种密码
假如以前我们数据库中的用户密码没有加密,或用别的方式加密,现在系统升级,新用户都使用BCrypt加密。
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{bcrypt}$2a$10$89rbg/..2V1hoRzXtlDa9ejjIzsqeO.kQgmkQnAa//xDzJLoyJgAu").authorities("auth").and()
.withUser("old").password("{noop}123").authorities("old");
此时不需要再设置passwordEncoder,而是在密码中加上前缀进行区分。如以前的用户old,给其密码加上前缀{noop},表示未加密。新用户密码前缀为{bcrypt},表示bcrypt加密。系统为根据前缀自动识别你的加密方式。在自认定认证中,同样可以根据前缀判断加密方式。
BCrypt密文解析
在密文中包含四段内容,$是分隔符。
2a:加密算法版本号。
10:加密轮次,默认为10,数值越大,加密时间和越难破解呈指数增长。可在BCryptPasswordEncoder构造参数传入。
第3个$之后:前面的内容是盐,后面的内容才是真正的密文。
以下方式可以更清晰的看出盐和全文。
String salt = BCrypt.gensalt(); //盐 默认参数轮次10
String result = BCrypt.hashpw("123", salt);//全文
System.out.println(salt);
System.out.println(result);