Spring Security密码加密工具类

1. 添加Spring Security依赖

<!--spring-security权限认证框架-->

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. 注入BCryptPasswordEncoder工具类Bean

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableSwagger2
@SpringBootApplication
@MapperScan("com.hundsun.one.mapper")
public class OneApplication {

    public static void main(String[] args) {
        SpringApplication.run(OneApplication.class, args);
    }

    /**
     * Spring Security权限认证框架 封装的密码加密工具类
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder getBCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

3. 生成密文及密文验证

@SpringBootTest
class OneApplicationTests {

    // spring security权限认证框架 封装的密码加密工具类
    @Autowired
    private BCryptPasswordEncoder pwdEncoder;

    @Test
    void xxx(){
        // 生成密文
        String encode = pwdEncoder.encode("123456");
        System.out.println("encode = " + encode);
        // 生成密文
        String encode1 = pwdEncoder.encode("123456");
        System.out.println("encode1 = " + encode1);
        // 验证密文
        boolean b = pwdEncoder.matches("123456", encode);
        System.out.println("b = " + b);
        // 验证密文
        boolean b1 = pwdEncoder.matches("123456", encode1);
        System.out.println("b1 = " + b1);
    }
}

4. 控制台打印结果

// 两次输入的明文都是123456,生成的密文却是不相同的
// 两次密文验证的结果都是true

encode = $2a$10$tKbmm6laeGZ2mDcn3EdP0OUy3OlWbN15.sJnFpcUSG1yoBYLGUfye
encode1 = $2a$10$51KayjetdJpMsWoomauz0OAp8ipaO6UOeSHCm01CW1I3gIkYyCr/.
b = true
b1 = true

Spring Security密码加密工具类

上一篇:VS Code 编译运行C/C++


下一篇:android studio 配置 Lombok 插件 -具体步骤