2014-11-04 185 views
1

我想散列&鹽用戶密碼與bcrypt和Spring安全性。春季安全自定義密碼鹽

這裏是我的用戶模型(我刪除無用的代碼):

public class User { 
    private Integer id; 
    private String email; 
    private String hashedPassword; 
    private String salt; //I want to use this salt. 
    private Boolean enabled; 

    //Getters & Setters 
} 

這是我如何創建新用戶用自己的鹽:

@Transactional 
public User create(String email, String password) { 
    User user = new User(); 
    user.setSalt(BCrypt.gensalt(12)); //Generate salt 
    user.setEnabled(true); 
    user.setEmail(email); 
    user.setHashedPassword(BCrypt.hashpw(password, user.getSalt())); 
    return dao.persist(user); 
} 

這裏是Spring配置:

<beans:bean id="userService" class="com.mycompany.service.UserService"/> 
<beans:bean id="myCustomUserDetailService" class="com.mycompany.service.MyCustomUserDetailService"/> 
<beans:bean id="bcryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/> 

<beans:bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource"> 
    <beans:property name="userPropertyToUse" value="salt"/> 
</beans:bean> 

<authentication-manager> 
    <authentication-provider user-service-ref="myCustomUserDetailService"> 
    <password-encoder ref="bcryptEncoder"> 
     <salt-source ref="saltSource"/> 
    </password-encoder> 
    </authentication-provider> 
</authentication-manager> 

在此配置中,我指出PasswordEncoder必須使用User.getSalt();

問題:我收到以下錯誤:與密碼模塊使用的PasswordEncoder時

鹽值必須爲null。

看着在stackoverflow後,鹽似乎必須爲空,因爲BCryptPasswordEncoder使用它自己的SaltSource。

  1. 有沒有辦法使用SaltSource的方法嗎?或
  2. 哪個可靠的算法可以讓我的SaltSource

謝謝。

+0

你想使用自己的鹽源的特定原因? – holmis83 2014-11-05 15:01:18

+0

@ holmis83我不知道'BCryptPasswordEncoder'是如何的,但我想爲每個用戶使用不同的salt,我希望能夠在多臺服務器上以相同的方式進行salt/check。 – 2014-11-05 15:24:11

回答

0

回答到第一個問題:

BCryptPasswordEncoder具有hardcoded鹽源(Bcrypt.getsalt)。
因此,不可能強制BCryptPasswordEncoder使用其他鹽源。無論如何,你可以嘗試子類,並添加自定義鹽屬性。