使用 BCryptPasswordEncoder 时获得相同的散列值 [英] Getting same hashed value while using BCryptPasswordEncoder

查看:36
本文介绍了使用 BCryptPasswordEncoder 时获得相同的散列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 BCryptPasswordEncoder 使用 Spring Security.现在对于更改密码,我需要做的是将用户提供的现有密码与 DB 值进行比较.

I am using spring security using BCryptPasswordEncoder. Now for change password what I need to do is to compare Existing Password provided by user with DB value.

但是由于盐是由 BCryptPasswordEncoder 动态生成的,每次我从下面的方法中获得不同的散列值时,它不一定会与我的数据库值匹配.

But since salt is generated dynamically by BCryptPasswordEncoder, every time I get different hashed value from below method and not necessarily it would match with my DB value.

public static String encodePassword(String password) {
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String hashedPassword = passwordEncoder.encode(password);
    return hashedPassword;
} 

解决这个问题的方法是什么?我可以识别用于我的数据库字段的盐并在上述方法中使用相同的盐吗?

What's the remedy for this problem? can I identify salt used for my DB field and use the same salt in above method ?

推荐答案

使用 PasswordEncoder 接口上的 matches 方法来检查密码是否有效,而不是编码再次并与现有哈希进行比较.

Use the matches method on the PasswordEncoder interface to check whether the password is valid, rather than encoding it again and comparing with the existing hash.

BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String existingPassword = ... // Password entered by user
String dbPassword       = ... // Load hashed DB password

if (passwordEncoder.matches(existingPassword, dbPassword)) {
    // Encode new password and store it
} else {
    // Report error 
}

这篇关于使用 BCryptPasswordEncoder 时获得相同的散列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆