常用的散列函数有 MD5 消息摘要算法、安全散列算法(Secure Hash Algorithm)。
Spring Security 提供了多种密码加密方案,官方推荐使用 BCryptPasswordEncoder,BCryptPasswordEncoder 使用 BCrypt 强哈希函数,开发者在使用时可以选择提供 strength 和 SecureRandom 实例。strength 越大,密钥的迭代次数越多,密钥迭代次数为 2^strength。strength 取值在 4~31 之间,默认为 10。
不同于 Shiro 中需要自己处理密码加盐,在 Spring Security 中,BCryptPasswordEncoder 就自带了盐,处理起来非常方便。
源码浅析 PasswordEncoder
PasswordEncoder 是一个接口,里边只有三个方法:
package org.springframework.security.crypto.password;
public interface PasswordEncoder {
String encode(CharSequence rawPassword);
boolean matches(CharSequence rawPassword, String encodedPassword);
default boolean upgradeEncoding(String encodedPassword) {
return false;
}
}
-
encode 方法用来对密码进行加密。
-
matches 方法用来对密码进行比对。
-
upgradeEncoding 表示是否需要对密码进行再次加密以使得密码更加安全,默认为 false。
PasswordEncoder 中的 encode 方法,是我们在用户注册的时候手动调用。
matches 方法,则是由系统调用,默认是在DaoAuthenticationProvider#additionalAuthenticationChecks 方法中调用的。
参考:
- https://mp.weixin.qq.com/s/jBoU5j4YChDVwyX22SbtgA