簡體   English   中英

Spring Security:加密密碼

[英]Spring Security : Encrypt password

我正在使用 spring 3.2.5。 現在我正在使用散列密碼

        MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
        messageDigest.update(password.getBytes("UTF-8"));
        byte[] digestBytes = messageDigest.digest();

我想使用 spring 提供的方法保護密碼。 我搜索了互聯網,大部分帖子都很舊。 所以任何例子都可以。

您可以使用org.springframework.security.crypto.password.StandardPasswordEncoder類。 它少了很多麻煩,您不必擔心鹽和迭代 - 細節完全封裝在編碼器中。

<!-- password encoder -->
<beans:bean id="encoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder" />


<!-- This is the authentication manager -->
<authentication-manager>
   <authentication-provider user-service-ref="authService">
    <password-encoder ref="encoder" />
   </authentication-provider>
</authentication-manager>

訪問網站以了解更多信息。

正如其他答案所建議的那樣,使用帶有<password-encoder>屬性的<password-encoder>是正確的。 我還想補充一點,建議的編碼器的用途是作為BCryptPasswordEncoder春DOC 建議嘗試使用老標准編碼器時:

 If you are developing a new system, BCryptPasswordEncoder is a better choice both in terms of security and interoperability with other languages.

您還可以在此處閱讀有關散列的更多背景詳細信息其中 BCrypt 算法也是建議的算法之一。

您可以簡單地使用 spring security 來完成,在 spring-security.xml bean 中添加以下行:

使用 SHA-512

    <authentication-manager>
        <authentication-provider user-service-ref="userDetailsService">
            <password-encoder hash="sha-512" />
        </authentication-provider>
    </authentication-manager>

或使用 md5

        <authentication-manager>
            <authentication-provider user-service-ref="userDetailsService">
                <password-encoder hash="md5" />
            </authentication-provider>
        </authentication-manager>

關於UserDetailsS​​ervice : UserDetailsS​​ervice 提供按用戶名加載用戶的方法。 更多關於 UserDetailsS​​ervice

如果您想通過電子郵件或手機號碼等任何其他屬性加載用戶,那么您需要編寫實現UserDetailsService自定義類並在該類中編寫您的實現。

請參閱此鏈接以獲取自定義 userDetailsS​​ervice 實現

我發現這是最簡單的方法,因此這是我使用的方法:

<sec:authentication-manager alias="authenticationManager">
    <sec:authentication-provider
        user-service-ref="userDetailsService">
        <sec:password-encoder hash="sha-256">
            <sec:salt-source user-property="username" />
        </sec:password-encoder>
    </sec:authentication-provider>
</sec:authentication-manager>

這里的要點是password-encoder是在 XML 本身中定義的(甚至是鹽,如果需要的話),所以不需要額外的代碼。 這就是“春天的方式”……

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM