如何使用 Spring Security 3 对密码进行哈希处理和加盐?
最佳答案
以编程方式,您可以按如下方式进行:
在您的 application-context.xml(在 contextConfigLocation
下的 web.xml 中定义)文件中定义 bean(本示例使用 md5
)。
<bean class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" id="passwordEncoder" />
然后 Autowiring 密码编码器:
@Autowired
PasswordEncoder passwordEncoder;
在您的方法或任何您想要散列和加盐的地方。
passwordEncoder.encodePassword("MyPasswordAsString", "mySaltAsStringOrObject");
上面的调用应该返回一个加盐的哈希(作为一个String
)。
应该这样做。我假设你能找出你需要的 jar 。
更新
不用说,使用 MD5 并不是最好的主意。理想情况下,您至少应该使用 SHA-256。这可以通过 ShaPasswordEncoder
来完成。 .
将上面的 MD5 bean 配置替换为:
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
<constructor-arg value="256"/>
</bean>
关于java - 使用 Spring Security 3 散列和加盐密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7378107/