BCryptPasswordEncoder 是一种使用 BCrypt 加密算法来加密密码的方法。它是在 Spring Security 中用来加密用户密码的一个类,其目的是为了防止密码被明文存储在数据库中。BCrypt 是一种强哈希算法,它能很好地防止被暴力破解。采用SHA-256 +随机盐+密钥对密码进行加密
首先导入依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.7.6</version>
</dependency>
编写配置类
package com.qingyun.kunba.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.security.SecureRandom;
@Data
@Configuration
@ConfigurationProperties(prefix = "encoder.crypt")
public class PasswordConfig {
/**
* 加密强度
*/
private int strength;
/**
* 干扰因子
*/
private String secret;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
//System.out.println("secret = " + secret);
//对干扰因子加密
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
//对密码加密
return new BCryptPasswordEncoder(strength, secureRandom);
}
}
配置yml
encoder:
crypt:
secret: ${random.uuid} # 随机的密钥,使用uuid
strength: 6 # 加密强度4~31,决定盐加密时的运算强度,超过10以后加密耗时会显著增加
接着就可以测试了
@Autowired
private BCryptPasswordEncoder encoder;
@Test
void savePassword() {
// encode():对明文字符串进行加密
//注册用户时,使用SHA-256+随机盐+密钥把用户输入的密码进行hash处理,得到密码的hash值,然后将其存入数据库中。
String pw = encoder.encode("abcd");
System.out.println(pw);
// matches():对加密前和加密后是否匹配进行验证
//用户登录时,密码匹配阶段并没有进行密码解密(因为密码经过Hash处理,是不可逆的),
// 而是使用相同的算法把用户输入的密码进行hash处理,得到密码的hash值,然后将其与从数据库中查询到的密码hash值进行比较。
// 如果两者相同,说明用户输入的密码正确。
System.out.println(encoder.matches("asdsad", pw));
System.out.println(encoder.matches("abcd", pw));
}
测试结果如下