Spring Security:加密密码

时间:2014-11-29 16:10:35

标签: spring spring-mvc spring-security

我使用的是弹簧3.2.5。现在我正在使用

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

我想使用spring提供的方法来保护密码。我搜索了互联网,大部分帖子都很老了。所以任何一个例子都没问题。

4 个答案:

答案 0 :(得分:4)

您可以使用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>

访问this网站了解详情。

答案 1 :(得分:4)

使用具有<password-encoder>属性的密码编码器作为其他答案建议是正确的。我还想在尝试使用旧的标准编码器时添加推荐的编码器使用BCryptPasswordEncoder作为Spring doc recommends

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

您还可以阅读有关散列here,的更多背景详细信息,其中BCrypt算法也是建议的算法之一。

答案 2 :(得分:3)

你可以使用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提供了通过用户名加载用户的方法。 More about UserDetailsService

如果您想通过电子邮件或手机号等任何其他属性加载用户,那么您需要编写实现UserDetailsService的自定义类并在该类中编写您的实现。

Refer this link for custom userDetailsService implementation

答案 3 :(得分:2)

我发现这是最简单的方法,因此这是我使用的方法:

<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本身中定义(如果需要,甚至是盐),因此不需要额外的代码。这是“春天的方式”......

相关问题