Spring Security 中的盐值加密

在 Spring Security 文档中有这么一句话: "盐值的原理非常简单,就是先把密码和盐值指定的内容合并在一起,再使用md5对合并后的内容进行演算,这样一来,就算密码是一个很常见的字符串,再加上用户名,最后算出来的md5值就没那么容易猜出来了。因为攻击者不知道盐值的值,也很难反算出密码原文。"

     呵呵, 问题如何理解这句话: "先把密码和盐值指定的内容合并在一起,再使用md5对合并后的内容进行演算".  例如, 在 applicationContext-security.xml 文件中的配置如下:

  


[xhtml] view plaincopy
01.<authentication-provider user-service-ref="userDetailsService">    
02.     <password-encoder hash="md5"> 
03.         <!-- 将每个用户的username作为盐值 --> 
04.         <salt-source user-property="username"/> 
05.     </password-encoder> 
06.</authentication-provider> 


   假设用户名是 Tom, 密码为 123456, 那么在数据库中存放的值应该是什么?

   通过查看 Spring Security 的 org.springframework.security.providers.encoding.BasePasswordEncoder 类可知 Spring Security 通过如下方式来匹配在数据库中已经被盐值加密的密码:  


[java] view plaincopy
01.protected String mergePasswordAndSalt(String password, Object salt, boolean strict) { 
02.        if (password == null) { 
03.            password = ""; 
04.        } 
05. 
06.        if (strict && (salt != null)) { 
07.            if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) { 
08.                throw new IllegalArgumentException("Cannot use { or } in salt.toString()"); 
09.            } 
10.        } 
11. 
12.        if ((salt == null) || "".equals(salt)) { 
13.            return password; 
14.        } else { 
15.            return password + "{" + salt.toString() + "}"; 
16.        } 
17.} 


   即通过 password + "{" + salt.toString() + "}" 中方式把 "密码和盐值指定的内容合并在一起". 所以对于用户名是 Tom, 密码为 123456 的用户在数据库中存放的密码应该为对 "123456{Tom}" md5 验算后的值: 610c492873b994f96f93e342a56bcd68

猜你喜欢

转载自gcq04552015.iteye.com/blog/1676640