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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章