2013-03-12 103 views
0

我介紹了Web應用程序的Spring安全性。首先,我有我的身份驗證管理器如下。Spring如何使用鹽編碼密碼

<authentication-manager> 
    <authentication-provider> 
     <password-encoder hash='md5'> 
     </password-encoder> 
     <jdbc-user-service data-source-ref="dataSource"/> 
    </authentication-provider> 
</authentication-manager> 

對於測試,我將使用'1'作爲用戶名和密碼。我使用了一個在線md5哈希生成器,併爲md5(1)獲得'c4ca4238a0b923820dcc509a6f75849b'。使用此配置登錄正常工作。我想嘗試鹽,我修改身份驗證管理器如下。

<authentication-manager> 
    <authentication-provider> 
     <password-encoder hash='md5'> 
      <salt-source user-property="username"/> 
     </password-encoder> 
     <jdbc-user-service data-source-ref="dataSource"/> 
    </authentication-provider> 
</authentication-manager> 

因此,正如我在網絡閱讀中使用的鹽是怎麼樣的哈希(鹽+密碼)。因此,使用相同的工具我散列'11',然後得到散列值'6512bd43d9caa6e02c990b0a82652dca'。我用該值更新數據庫。但是現在,登錄失敗,並顯示錯誤「導致:錯誤憑據」。這意味着密碼與數據庫不匹配。所以我的問題是,這是否意味着Spring使用不同的方式進行醃製?

+2

使用[BCrypt](http://stackoverflow.com/a/8528804/241990)。它更安全,醃製自己照顧。 MD5對於哈希密碼並不是一個好的選擇。 – 2013-03-12 17:51:43

+0

應該試試。謝謝盧克 – 2013-03-13 04:55:53

回答

0

該死的無論如何,春季鹽醃的方法是不同的。用戶遵循Java代碼來計算與鹽的哈希值。

public static void main(String[] args) { 
    Md5PasswordEncoder md5 = new Md5PasswordEncoder(); 
    String hash = md5.encodePassword("1", "1"); 
    System.out.println(hash); 
} 

我得到了 '6a8a1f634e38d30e87b450899b31f810' 作爲加密的密碼(右不同?)。然後我將它插入數據庫並嘗試我的應用程序登錄。佛拉!登錄成功。

2

由於您使用的是spring安全性,因此您可以考慮使用PasswordEncoder bean。

<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> 
</beans:bean> 

和你的認證管理器會是這樣(其他城市碼):

<authentication-manager> 
    <authentication-provider> 
     <password-encoder ref="passwordEncoder"> 
      <salt-source user-property="username"/> 
     <password-encoder/> 
     <jdbc-user-service data-source-ref="dataSource"/> 
    </authentication-provider> 
</authentication-manager> 

訪問Spring Security Custom Authentication and Password Encoding & Spring Security:password encoding in DB and in applicationContext知道更多。

+0

使用財產「哈希」也是這樣嗎?我認爲這與明確創建一個bean是一樣的。注入一個org.springframework.security.authentication.encoding.ShaPasswordEncoder作爲PasswordEncoder可以輕鬆做到以下幾點嗎? <認證管理器> <認證提供商> <密碼編碼器的散列= 「SHA」> <鹽源用戶屬性= 「用戶名」/> <密碼編碼器/> 2013-03-13 05:00:46

+0

你就在那裏。 – 2013-03-13 05:03:20