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

查看:259
本文介绍了使用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动态生成的,因此每次我从下面的方法中获得不同的哈希值时,不一定与我的DB值匹配.

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方法检查密码是否有效,而不是再次对其进行编码并与现有哈希进行比较./p>

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天全站免登陆