Spring security中的BCryptPasswordEncoder方法对密码进行加密与密码匹配

1.BCryptPasswordEncoder使用之前要加入依赖

如果是SSM加入的依赖

1
2
3
4
5
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>5.1.4.RELEASE</version>
 </dependency>

  

如果是SpringBoot加入的依赖

1
2
3
4
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring‐boot‐starter‐security</artifactId>
  </dependency>

 

1
2
3
4
5
6
7
BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
加密:
bcryptPasswordEncoder.encode(password);
 
//password是输入的密码,encodedPassword是通过bcryptPasswordEncoder进行加密的密码
解密:
bcrytPasswordEncoder.matches(password,encodedPassword)

  

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.qingfeng.service.impl;
 
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
 
public class Test {
 
    public static void main(String[] args) {
         
        String password = "123456";
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
 
        //加密:bcryptPasswordEncoder进行密码加密
        String encodedPassword = bcryptPasswordEncoder.encode(password);
        System.out.println("bcryptPasswordEncoder进行密码加密:"+encodedPassword);
 
        //解密:
        boolean flag = bcryptPasswordEncoder.matches(password, encodedPassword);
        //如果flag为true,则解密成功  false,则解密失败
        System.out.println("解密:"+flag);
 
    }
 
}

测试结果:

1
2
3
bcryptPasswordEncoder进行密码加密:$2a$10$z1l7KwMFGthgsNOg6h0I4OVTUUyhC11paX1PN8glw7bT3tL4feZ1u
 
解密:true

  

  

 

posted @   Amy清风  阅读(2968)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示