版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/u012211603/article/details/81659907
以往一般都用MD5加盐进行密码加密, 现在正好使用Spring Security安全框架, 那么就来了解一下如何使用 BCryptPasswordEncoder进行密码加密。
#####一. BCryptPasswordEncoder源码的大致理解
public class BCryptPasswordEncoder implements PasswordEncoder
public interface PasswordEncoder {
String encode(CharSequence var1);
boolean matches(CharSequence var1, String var2);
}
BCryptPasswordEncoder
实现了PasswordEncoder
接口,需要实现其加密和密码匹配的方法。
public BCryptPasswordEncoder() {
this(-1);
}
public BCryptPasswordEncoder(int strength) {
this(strength, (SecureRandom)null);
}
public BCryptPasswordEncoder(int strength, SecureRandom random) {
this.BCRYPT_PATTERN = Pattern.compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}");
this.logger = LogFactory.getLog(this.getClass());
this.strength = strength;
this.random = random;
}
public String encode(CharSequence rawPassword) {
String salt;
if (this.strength > 0) {
if (this.random != null) {
salt = BCrypt.gensalt(this.strength, this.random);
} else {
salt = BCrypt.gensalt(this.strength);
}
} else {
salt = BCrypt.gensalt();
}
return BCrypt.hashpw(rawPassword.toString(), salt);
}
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if (encodedPassword != null && encodedPassword.length() != 0) {
if (!this.BCRYPT_PATTERN.matcher(encodedPassword).matches()) {
this.logger.warn("Encoded password does not look like BCrypt");
return false;
} else {
return BCrypt.checkpw(rawPassword.toString(), encodedPassword);
}
} else {
this.logger.warn("Empty encoded password");
return false;
}
}
使用SecureRandom
生成的强(安全)随机数作为盐进行加密,不需要我们去记录这个盐,因为它会直接混在加密后的密码串中。
加密与匹配都是调用了BCrypt类中的方法。
#####二.具体使用
1.加密很简单,创建BCryptPasswordEncoder
类后调用其encode
方法,把待加密的密码作为参数传进去得到加密后的密码,设置密码为加密后的密码再进行新增操作。
...
...
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
// 加密
String encodedPassword = passwordEncoder.encode(user.getPassword().trim());
user.setPassword(encodedPassword);
...
...
2.在进行密码匹配时,如登陆操作,不用另外写匹配方法,在配置文件中进行配置即可,这里使用xml的形式进行配置。
(关于Spring Security配置文件的别的内容省略)
首先要配置BCryptPasswordEncoder这个Bean
<beans:bean id="bCryptEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
接下去只要在认证管理器的用户认证中引用这个加密方式即可,在登陆时会自行进行密码匹配。
(用户认证:需要创建一个类实现UserDetailsService
,实现其loadUserByUsername
方法,会对用户名,密码,权限集等等进行判断)
<!-- 认证管理器 -->
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder ref="bCryptEncoder"/>
</authentication-provider>
</authentication-manager>
数据库中加密后的密码串参考:
$2a$10$XLKswJdEFnyFRkVU4CmoPe1uX6roiDRPYhLOV3dI22/A/r1TVC36S
随意记录一下,省得我个猪脑不知道下回用的时候就忘了呢。