BCrypt 简介
BCrypt是一种不可逆的加密算法。使用随机盐,并将随机盐保存到密文中,不用单独存到数据库,更安全。
加密原理: hash( 密码 + 随机盐) * 加密次数。
使用BCrypt能实现每次加密的值都是不一样的,因为每次的随机盐都不同。
BCrypt 使用
- 引入依赖
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
- 配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.security.SecureRandom;
@Configuration
public class PasswordConfig {
/**
* 随机种子的长度
*/
private int seedLength = 32;
/**
* 加密强度4~31,决定了密码和盐加密时的运算次数,超过10以后加密耗时会显著增加
*/
private Integer strength = 10;
@Bean
public BCryptPasswordEncoder passwordEncoder() {
// 加密前度,数字越大强度越大,越安全,越耗时
SecureRandom random = new SecureRandom(SecureRandom.getSeed(seedLength));
return new BCryptPasswordEncoder(strength, random);
}
}
- 加密,解密
package bcrypt;
import com.heima.admin.AdminApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = AdminApplication.class)
@RunWith(SpringRunner.class)
public class BCryptTest {
@Autowired
private BCryptPasswordEncoder encoder;
@Test
public void test() {
//--------加密---------
//密码
String password = "123456";
//使用BCrypt进行加密
String newPwd = encoder.encode(password);
System.out.println("密文为:" + newPwd);
//--------解密---------
//使用BCrypt进行解密,传入 密码、密文
boolean b = encoder.matches(password, newPwd);
System.out.println("前后密码是否一致: " + b);
}
}