2017-02-24 83 views
2

我正在使用Spring MVC,我想加密以dB爲單位保存的密碼,我查看了其他線程,並且他們建議使用MD5。使用MD5是否是一種好習慣,或者Spring中是否有其他方法來實現它?Spring MVC中的密碼加密

+1

如果您正在使用彈簧安全,你可以使用Spring Security密碼編碼器也可以和實現你自己的 –

回答

0

你能澄清,如果你正在尋找春季安全或者Spring MVC。你的問題標題是「」Spring MVC中的密碼加密「,而你已經爲Spring Security標記了這個問題。

春季安全建議使用以下 org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder

http://docs.spring.io/spring-security/site/docs/4.2.1.RELEASE/reference/html/core-services.html#core-services-password-encoding

+1

我正在尋找密碼加密在Spring Security – Ramanathan

+0

好,我已經分享了Spring參考頁面的相關鏈接。如果您需要任何幫助,請添加評論。 – bhrt

0

否;使用BCrypt - 可在BCryptPasswordEncoder的Spring中使用。

1

不要使用MD5,MD5哈希的問題在於它的執行速度相對較快,如果有人得到哈希值,他們可以很容易地蠻力。還有彩虹表,它們是密碼列表及其關聯的MD5散列。

正如@Jan Nielsen所言,BCrypt遠遠優越。我個人使用PBKDF2。這兩種方法都是通過在生成散列時使用隨機鹽來工作的。在數據庫中存儲salt和哈希密碼。我希望更進一步,並存儲用於創建散列的迭代次數。

這是一個關於密碼加密的好博客,其中詳細介紹了代碼示例的更多細節。 https://crackstation.net/hashing-security.htm

1

你可以使用BCryptPasswordEncoder來編碼你的密碼,爲了做到這一點,你需要創建一個這個類的bean。

@Bean 
public PasswordEncoder passwordEncoder() { 
    return new BCryptPasswordEncoder(); 
} 

雖然註冊(保存新的用戶數據庫)你的用戶,你可以自動線PasswordEncoder並調用encode方法編碼密碼

@Autowired PasswordEncoder passwordEncoder; 

public User registerUser(User user){ 
    // other logic 

    String encryptedPassword = passwordEncoder.encode(user.getPassword()); 
    user.setPassword(encryptedPassword); 

    //logic to save the user to DB 
} 
+0

感謝您的回答,但我不明白,如果我通過這種方式加密密碼當我嘗試登錄時密碼如何匹配?因爲如果我沒有錯誤'BCryptPasswordEncoder'所有時間都會生成不同的值。通過我對Spring的新方法:) –

+0

當您嘗試登錄時,如果您將密碼作爲簡單文本傳遞給登錄方法,那麼您將需要再次調用密碼的用戶提供的密碼上的編碼方法,然後再比較 –