Spring Security PasswordEncoder 的使用
Spring 中,提供了对于密码加密加盐的方法,我们可以通过引入依赖来方便的使用。它相对于MD5方法的优势在于:他的提供了加盐的选择,相反MD5的安全性在降低,可以通过彩虹表等方法来破解MD5的一部分密码。下面是具体的使用方法:
1.依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
2.注入bean
@Configuration
public class PasswordEncoderConfig {
private static final Logger logger = LoggerFactory.getLogger(PasswordEncoderConfig.class);
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
if (passwordEncoder instanceof DelegatingPasswordEncoder) {
((DelegatingPasswordEncoder)passwordEncoder).setDefaultPasswordEncoderForMatches(NoOpPasswordEncoder.getInstance());
}
logger.debug("PasswordEncoderConfig passwordEncoder is {}", JSON.toJSONString(passwordEncoder));
return passwordEncoder;
}
}
3.具体的引用
@Autowired
private PasswordEncoder passwordEncoder;
4.方法
/**
* Encode the raw password. Generally, a good encoding algorithm applies a SHA-1 or
* greater hash combined with an 8-byte or greater randomly generated salt.
*/
String encode(CharSequence rawPassword);
/**
* Verify the encoded password obtained from storage matches the submitted raw
* password after it too is encoded. Returns true if the passwords match, false if
* they do not. The stored password itself is never decoded.
*
* @param rawPassword the raw password to encode and match
* @param encodedPassword the encoded password from storage to compare with
* @return true if the raw password, after encoding, matches the encoded password from
* storage
*/
boolean matches(CharSequence rawPassword, String encodedPassword);