BCryptPasswordEncoder 判断密码是否相同

加密

BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
encode.encode(password);

比较

matches(CharSequence rawPassword, String encodedPassword)    

需要通过自带的方法 matches 将未经过加密的密码和已经过加密的密码传进去进行判断,返回布尔值。

举例

复制代码
public class BCryptPasswordEncoderTest {
    public static void main(String[] args) {
        String pass = "admin";
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String hashPass = bcryptPasswordEncoder.encode(pass); 
        System.out.println(hashPass);
 
        boolean flag = bcryptPasswordEncoder.matches("admin",hashPass);
        System.out.println(flag); 
    }
}
复制代码

可以看到,每次输出的hashPass 都不一样,但是最终的flag都为 true,即匹配成功。

查看代码,可以看到,其实每次的随机盐,都保存在hashPass中。在进行matchs进行比较时,调用BCrypt 的String hashpw(String password, String salt)方法。两个参数即”admin“和 hashPass。

复制代码
//******BCrypt.java******salt即取出要比较的DB中的密码*******
real_salt = salt.substring(off + 3, off + 25);
try {
// ***************************************************
    passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8");
}
catch (UnsupportedEncodingException uee) {}
saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);
B = new BCrypt();
hashed = B.crypt_raw(passwordb, saltb, rounds);
复制代码

假定一次hashPass为:$2a$10$AxafsyVqK51p.s9WAEYWYeIY9TKEoG83LTEOSB3KUkoLtGsBKhCwe

随机盐即为 AxafsyVqK51p.s9WAEYWYe(salt = BCrypt.gensalt();中有描述),可见,随机盐(AxafsyVqK51p.s9WAEYWYe),会在比较的时候,重新被取出。

即,加密的hashPass中,前部分已经包含了盐信息。

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