1.BCrypt简介

任何应用考虑到安全,绝不能明文的方式保存密码。密码应该通过哈希算法进行加密。
有很多标准的算法比如SHA或者MD5,结合salt(盐)是一个不错的选择。 Spring Security
提供了BCryptPasswordEncoder类,实现Spring的PasswordEncoder接口使用BCrypt强
哈希方法来加密密码。
BCrypt强哈希方法 每次加密的结果都不一样。

2.BCrypt使用

(1)tensquare_user工程的pom引入依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring‐boot‐starter‐security</artifactId>
  4. </dependency>

(2)添加配置类 (资源/工具类中提供)

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

  1. /**
  2. * 安全配置类
  3. * WebSecurityConfigurerAdapter 所有springSecurity的配置文件都可以选择此类进行配置
  4. */
  5. @Configuration
  6. @EnableWebSecurity
  7. public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
  8. @Override
  9. protected void configure(HttpSecurity http) throws Exception {
  10. http
  11. .authorizeRequests()
  12. .antMatchers("/**").permitAll()
  13. .anyRequest().authenticated()
  14. .and().csrf().disable();
  15. }
  16. }

(3)修改tensquare_user工程的Application, 配置bean

@Bean    
public BCryptPasswordEncoder bcryptPasswordEncoder(){    
return new BCryptPasswordEncoder();        
}

(4)在代码中使用加密以及加密的校验

注意:使用BCrypt做加密是不可逆的,故没有解密之说,如果想要校验,需使用提供的matches()进行校验

加密

@Autowired    
BCryptPasswordEncoder encoder;    

public void add(Admin admin) {    
admin.setId(idWorker.nextId()+""); //主键值        
//密码加密 使用encode()方法       
String newpassword = encoder.encode(admin.getPassword());//加密后
的密码

admin.setPassword(newpassword);                  
adminDao.save(admin);        
}

加密后的校验

(1)AdminDao增加方法定义

  public Admin findByLoginname(String loginname);

(2)AdminService增加方法

/**    
 * 根据登陆名和密码查询    
 * @param loginname    
 * @param password    
 * @return    
 */    
public Admin findByLoginnameAndPassword(String loginname, String
password){

Admin admin = adminDao.findByLoginname(loginname);    

// 密码校验使用matches()方法
if( admin!=null && encoder.matches(password,admin.getPassword()))
{

return admin;            
}else{        
return null;            
}        
}