一.概述
用户表的密码通常使用MD5等不可逆算法加密后存储,为防止彩虹表破解更会先使用一个特定的字符串(如域名)加密,然后再使用一个随机的salt(盐值)加密。 特定字符串是程序代码中固定的,salt是每个密码单独随机,一般给用户表加一个字段单独存储,比较麻烦。 BCrypt算法将salt随机并混入最终加密后的密码,验证时也无需单独提供之前的salt,从而无需单独处理salt问题。
二.在spring-security框架中添加BCrypt
部分业务代码
public Result add(@RequestBody TbSeller seller){ //密码加密 BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String password = passwordEncoder.encode(seller.getPassword()); seller.setPassword(password); try { sellerService.add(seller); return new Result(true, "增加成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "增加失败"); } }
spring-security.xml ,添加如下配置
<beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
修改认证管理器的配置
<!-- 认证管理器 --> <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref='userDetailService'> <password-encoder ref="bcryptEncoder"></password-encoder> </authentication-provider> </authentication-manager>