spring security3.x学习(18)_salt以及Bcrypt加密

来源:互联网 发布:淘宝女装模特拍摄教程 编辑:程序博客网 时间:2024/05/21 10:33
其实,对于基本的权限基础操作我们已经学的差不多了,接下来应该都是一堆复杂或深入的知识了,。呵呵。不过越学越有点意思了。这3天假期也没有浪费啊。 

这次看一下登录的加密:

[html] view plaincopy
  1. <authentication-manager alias="authenticationManager">  
  2.   <authentication-provider user-service-ref="jdbcUserService">  
  3.     <password-encoder hash="sha"/>  
  4.   </authentication-provider>  
  5. </authentication-manager>   

这里在authentication-provider中配置了一个password-encoder标签,其中有个属性叫做hash,就是要加密密码所用的加密方法。看看都可以选用哪些系统默认提供的呢?:

看一看书中的介绍:

看到这里,我又去查了一下最新的官方文档,文档中这样写:

他建议我们使用BCryptPasswordEncoder类。上面我们提供了一种方式是使用hash的方式进行配置,其实还有一种方式,通过ref进行配置:
< bean class = "org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" id = "passwordEncoder"/>

<authentication-manager alias="authenticationManager">
          <authentication-provider user-service-ref="jdbcUserService">
               <password-encoder ref="passwordEncoder"/>
          </authentication-provider>
</authentication-manager>
虽然这样配置spring security文档中也说可以了,但是它还是建议我们加一些"盐值"(salt),加上这个以后就更难破解了。

[html] view plaincopy
  1. <authentication-manager alias="authenticationManager" >  
  2.         <authentication-provider user-service-ref="jdbcUserService" >  
  3.             <password-encoder ref="passwordEncoder" >  
  4.                 <salt-source ref="saltSource" />  
  5.             </password-encoder>  
  6.         </authentication-provider>  
  7. </authentication-manager >  

。那么这个salt有什么用呢。看如下这个图:

好的,那流程我们就应该知道了,用户通过输入密码然后通过和salt值连接进行计算加密保存到用户数据库中,如果salt越过于随机就越不好破解。
注意:“需要记住的是salt被添加到明文的密码上,所以salt不能进行单向的加密,因为应用要查找用户对应的salt值以完成对用户的认证。”
Spring Security为我们提供了一个接口o.s.s.authentication.dao.SaltSource,它定义了一个方法根据UserDetails来返回salt值,并提供了两个内置的实现:
1.SystemWideSaltSource为所有的密码定义了一个静态的salt值。这与不使用salt的密码相比并没有提高多少安全性; (那这个就应该是不推荐使用呗!)
2.  ReflectionSaltSource使用UserDetails对象的一个bean属性得到用户密码的salt值。 鉴于salt 值应该能够根据用户数据得到或者与用户数据一起存储,ReflectionSaltSource作为内置的实现被广泛使用。
看一下配置方法:
[html] view plaincopy
  1. <bean  class="org.springframework.security.authentication.dao.ReflectionSaltSource" id="saltSource">  
  2.   <property name="userPropertyToUse" value="username"/>  
  3. </bean>  

userPropertyToUser是UserDetails对象的一个属性值(ReflectionSaltSource类是通过反射获取属性值的)
[html] view plaincopy
  1. <authentication-manager alias="authenticationManager">  
  2.   <authentication-provider user-service-ref="jdbcUserService">  
  3.     <password-encoder ref="passwordEncoder">  
  4.        <salt-source ref="saltSource"/>  
  5.     </password-encoder>  
  6.   </authentication-provider>  
  7. </authentication-manager>  

那么现在有一个问题,就是salt值是通过什么来获取的呢。

应该是依赖UserDetails来获取的、

突然想到了spring security文档中给我们的建议。他不是希望我们能使用Bcrpt加密方式吗。然后我就去查了文档中,关于Bcrpt的介绍,发现,我不用像书中写的那样复杂,要完成很多的salt过程,这些都不用,我们看一下文档:

多有意思哈。 看看。多查文档好啊。。那么我们看到了它的便利,我们怎么使用它呢。 我写了一段代码:
[html] view plaincopy
  1. BCryptPasswordEncoder util = new BCryptPasswordEncoder();  
  2. String password = util.encode("admin" );  
  3. System. out.println(util.matches("admin" , password));  
这样以后,输出的是true.这个Bcrypt很有意思,他每次加密的值是不一样的。可能是因为他内部有随机salt的语言吧。 给大家看一下我的测试代码:
[html] view plaincopy
  1. BCryptPasswordEncoder util = new BCryptPasswordEncoder();  
  2. for(int i = 0 ; i < 10; i ++){  
  3.       System. out.println(util.encode("admin" ));  
  4. }  

输出结果是:
[html] view plaincopy
  1. $2a$10$zYH/GUMQ1reN.OfyMg2Rh.TYdKwerqF0iSzEDtUcu1eZl6uP5wtuC  
  2. $2a$10$z7ksuaRgAgSnbgftvI9lGevhxX0qliy90m5f0e6jUs8mYGL1b6MYO  
  3. $2a$10$pjA1zF0T5uaiwnNPVOIpjuHYpdRdWnCJnVBOi2IrFzUv8S9cmh4qC  
  4. $2a$10$5sT9FVFiWDPUbdIy/hKzVO7fHWbw.C30PPm5BaZ2Aj5PZTzJXUHK2  
  5. $2a$10$xjAGP2GdHCtCs8MZp/YqcOsPohLP1vK46A2kDak0rAkvUqF7HQTN2  
  6. $2a$10$gzpMfQdGVmrDaYbPUOSwee8JSON7DyC5Ix8roR/YFNrnHEOT9E.V.  
  7. $2a$10$27FasVFxg2u84oX0XATmo.JuwdBQaW6RYUYqD6fLa5zvE0rVOCL3m  
  8. $2a$10$2J4McbDdQXi6OhtCFBaF0ezISxII33ECVDWhl/q6p1EznGmsUSIeK  
  9. $2a$10$QZNF4fH7qh5c684aiGuc3.6vsLa7VYMlWd1PYNxli4zabVxrF8JxS  
  10. $2a$10$2P78iMXhmFfNlUNKhn/ZPeJfhGzgIEBbSWpYPhkCQ8qAr60Z6lmS.  


看到了没?、 都是不一样的。 呵呵。 我们看一下他的源码
[html] view plaincopy
  1. /*    */ package org.springframework.security.crypto.bcrypt;  
  2. /*    */  
  3. /*    */ import java.security.SecureRandom;  
  4. /*    */ import java.util.regex.Matcher;  
  5. /*    */ import java.util.regex.Pattern;  
  6. /*    */ import org.apache.commons.logging.Log;  
  7. /*    */ import org.apache.commons.logging.LogFactory;  
  8. /*    */ import org.springframework.security.crypto.password.PasswordEncoder;  
  9. /*    */  
  10. /*    */ public class BCryptPasswordEncoder  
  11. /*    */    implements PasswordEncoder  
  12. /*    */ {  
  13. /*    */    private Pattern BCRYPT_PATTERN;  
  14. /*    */    private final Log logger ;  
  15. /*    */    private final int strength ;  
  16. /*    */    private final SecureRandom random;  
  17. /*    */  
  18. /*    */    public BCryptPasswordEncoder ()  
  19. /*    */    {  
  20. /* 42 */     this(-1);  
  21. /*    */    }  
  22. /*    */  
  23. /*    */    public BCryptPasswordEncoder( int strength)  
  24. /*    */    {  
  25. /* 49 */     this(strength, null);  
  26. /*    */    }  
  27. /*    */  
  28. /*    */    public BCryptPasswordEncoder( int strength, SecureRandom random)  
  29. /*    */    {  
  30. /* 34 */     this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");  
  31. /* 35 */     this.logger = LogFactory.getLog(super.getClass());  
  32. /*    */  
  33. /* 58 */     this.strength = strength;  
  34. /* 59 */     this.random = random;  
  35. /*    */    }  
  36. /*    */  
  37. /*    */    public String encode(CharSequence rawPassword)  
  38. /*    */    {  
  39. /*    */      String salt;  
  40. /*    */      String salt;  
  41. /* 64 */     if (this. strength > 0)  
  42. /*    */      {  
  43. /*    */        String salt;  
  44. /* 65 */       if (this. random != null) {  
  45. /* 66 */         salt = BCrypt.gensalt(this. strength, this.random );  
  46. /*    */        }  
  47. /*    */        else  
  48. /* 69 */         salt = BCrypt.gensalt(this. strength);  
  49. /*    */      }  
  50. /*    */      else  
  51. /*    */      {  
  52. /* 73 */       salt = BCrypt.gensalt ();  
  53. /*    */      }  
  54. /* 75 */     return BCrypt.hashpw(rawPassword.toString(), salt);  
  55. /*    */    }  
  56. /*    */  
  57. /*    */    public boolean matches(CharSequence rawPassword, String encodedPassword) {  
  58. /* 79 */     if ((encodedPassword == null) || (encodedPassword.length() == 0)) {  
  59. /* 80 */       this.logger.warn( "Empty encoded password");  
  60. /* 81 */       return false;  
  61. /*    */      }  
  62. /*    */  
  63. /* 84 */     if (!(this.BCRYPT_PATTERN .matcher(encodedPassword).matches())) {  
  64. /* 85 */       this.logger.warn( "Encoded password does not look like BCrypt");  
  65. /* 86 */       return false;  
  66. /*    */      }  
  67. /*    */  
  68. /* 89 */     return BCrypt.checkpw(rawPassword.toString(), encodedPassword);  
  69. /*    */    }  
  70. /*    */ }  

看一下,他内部真的使用了SecureRandom 这个随机类。然后加密的时候也使用了自己计算出来的一个salt然后进行加密的,这个要比我们自己配置salt要好的多。所以建议我们以后都使用Bcrypt加密方式了。
0 0
原创粉丝点击