spring security中 BCrypt密码加密算法

任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过哈希算法进行加密。
有很多标准的算法比如 SHA 或者 MD5 ,结合 salt( ) 是一个不错的选择。
 
spring security中有多种密码加密方式,MD5算法的Md5PasswordEncoder、SHA 算法的ShaPasswordEncoder,但由于是弱加密算法,都被弃用了。推荐使用的是BCrypt算法的BCryptPasswordEncoder。
BCryptPasswordEncoder  实现Spring PasswordEncoder 接口使用 BCrypt
哈希方法来加密密码。
BCrypt 强哈希方法 每次加密的结果都不一样。


@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)

 

 
1 工程的 pom 引入依赖
 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

 
2 )添加配置类 (资源 / 工具类中提供)
我们在添加了 spring security 依赖后,所有的地址都被 spring security 所控制了,我们目
前只是需要用到 BCrypt 密码加密的部分,所以我们要添加一个配置类,配置为所有地址
都可以匿名访问。
 

 

@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())
/**
* 根据手机号和密码查询用户
* @param mobile
* @param password
* @return
*/
public User findByMobileAndPassword ( String mobile , String password ){
    User user = userDao . findByMobile ( mobile );
    if ( user!= null && encoder . matches ( password , user . getPassword ())){
        return user ;
    } else {
        return null ;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值