当前位置:   article > 正文

Spring boot中如何对用户密码进行加密_springboot密码加密

springboot密码加密

1、添加commons-codec依赖

<!--        加密依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2、在boot的启动类中声明。

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
  • 1
  • 2
  • 3
  • 4

3、关掉权限验证。
在boot的启动类头部加上下面这个注解就可以关掉权限验证。

@EnableAutoConfiguration(exclude = {org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class })
  • 1

4、注入到要使用的业务中

 @Autowired
    private BCryptPasswordEncoder passwordEncoder;
  • 1
  • 2

5、使用
加密

 //加密,strs要加密的字符串
        String strs="test";
        for (int i = 0; i < 3; i++) {
            System.out.println("第"+i+"次加密:"+passwordEncoder.encode(strs));
        }
  • 1
  • 2
  • 3
  • 4
  • 5

输出结果:
在这里插入图片描述
我们可以看出虽然明文都一样,但是加密结果都是不一样的
验证明文密码和加密后的密码

//明文密码
        String strs="test";
        //加密过的密码,名文都是test
        List<String> encodeList = new ArrayList<>();
        encodeList.add("$2a$10$XHsBzIixVCQnTmGVTzQL..yNOpnGMf8hd1RUyiKCbbvJVYIb2vEp6");

        encodeList.add("$2a$10$4Ri2UCscYMeBfnMuiWH0c./3Uz3kCFaddFjBq3yeQLWZOO6Ef8gKq");
        encodeList.add("$2a$10$R7uwcxsGo5Ox78QAOkOltOsnCGL505NiFlpRuba4iCiS4yXYGpn82");
        //其它加密后的明文密码
        encodeList.add("$2a$10$ijITqdz.PAss3yQxb/iAueVP8a5W2lqUT1JrxNihpmmQXXmnhn3ry");

        //验证明文密码和加密后的密码
        for (int i = 0; i < encodeList.size(); i++) {
            System.out.println(passwordEncoder.matches(strs,encodeList.get(i)));
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

输出结果:在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/911077
推荐阅读
相关标签
  

闽ICP备14008679号