【SpringSecurity】BCrypt密码加密和解密 一文学会使用BCryptPasswordEncoder

2年前 (2022) 程序员胖胖胖虎阿
281 0 0

BCrypt就是一款加密工具,可以比较方便地实现数据的加密工作。也可以简单理解为它内部自己实现了随机加盐处理。例如,使用MD5加密,每次加密后的密文其实都是一样的,这样就方便了MD5通过大数据的方式进行破解。
BCrypt生成的密文是60位的,而MD5的是32位的。

BCryptPasswordEncoder 是 Spring Security 官方推荐的密码解析器。BCryptPasswordEncoder 类是PasswordEncoder接口的实现类。
BCryptPasswordEncoder 是对 BCrypt 强散列方法的具体实现。是基于 Hash 算法实现的单向加密。可以通过 strength 控制加密强度,默认 10.

使用BCrypt能实现每次加密的值都是不一样的。

在PasswordEncoder接口中有三个方法:

  • String encode(CharSequence rawPassword):加密原始密码。而BCrypt实现类会随机生成的salt来进行加密。
  • boolean matches(CharSequence rawPassword, String encodedPassword):对加密的密码和传入的原始密码进行验证。如果密码匹配则返回true,否则返回false。存储的密码本身永远不会被解码。
    • rawPassword:原始密码,比如加密前密码是“123”,这里就传入“123”
    • encodedPassword:加密后的密码
  • boolean upgradeEncoding(String encodedPassword):如果加密后的密码需要重新加密以提高安全性,则返回true,否则返回false。默认返回false。
    • encodedPassword:加密后的密码

需要的maven依赖:

<!-- SpringBoot项目中的依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 非SpringBoot项目的依赖,SpringBoot项目也能用 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
</dependency>

测试方法

public class BcryptTest {
    public static void main(String[] args) {
        // 用户密码
        String password = "123123";
        // 创建密码加密的对象
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        // 密码加密
        String newPassword = passwordEncoder.encode(password);
        System.out.println("加密后的密码为:" + newPassword);

        // 校验这两个密码是否是同一个密码
        // matches方法第一个参数是原密码,第二个参数是加密后的密码
        boolean matches = passwordEncoder.matches(password, newPassword);
        System.out.println("两个密码一致:" + matches);
    }
}

执行结果:
【SpringSecurity】BCrypt密码加密和解密 一文学会使用BCryptPasswordEncoder

相关文章

暂无评论

暂无评论...