无法让 Bcrypt.checkpw 在 java play 框架中验证密码



几年前我写了一个应用程序,升级了一些jars,但没有升级bcrypt

它是使用play框架用java编写的。

BCrypt 由 "org.mindrot" % "jbcrypt" % "0.3m" 提供

我使用 BCrypt.checkpw(password.trim((, user.getPassword(((

其中密码是捕获的明文,user.getPassword 是存储在 mysql 中的哈希,存储为 char(60(。

I 使用 BCrypt.hashpw(password.trim((, BCrypt.gensalt(15(( 哈希密码

Checkpw 使用原始密码很有趣,但任何新密码都会失败并且总是响应错误

一个有趣的观察是,我的开发数据库中有一个密码,我知道它是"密码" 它的哈希值看起来像这样

$2a$10$UvKgjjT./SuMlD6gsoyD0e2lBcOwFtL/mfGmneTou/lrU1R/ZwMLK

我刚刚创建的新密码并将其密码设置为"密码">

它的哈希值看起来像这样

$2a$10$rNJzD52/muHMkBF1Co9XF.VkQNRHQ3HCW.DYzke7jnY424voZwyq6

我知道它们应该有所不同,但格式看起来有些不同?

请感谢任何帮助,因为这毫无意义,因为没有任何变化,但新用户无法注册

法典: 密码在我的用户类中设置

public void setPassword(String password) {
play.Logger.debug("setPassword |" + password.trim() +"|");
this.password = BCrypt.hashpw(password.trim(), BCrypt.gensalt(15));
}

我在我的注册方法中调用它

public Result registeruser() {
JsonNode json = request().body().asJson();
.
.
.
if (json.has("password")) {
user.setPassword(json.findPath("password").textValue())
}
.
.
.
user.save()
.
.
.
}

然后我有以下身份验证方法

public static Users authenticate(String email, String password) {
play.Logger.debug("email is " + email);
play.Logger.debug("authenticate password entered |" + password.trim() +"|");
Users user = Users.find.query().where().eq("email", email).findOne();
if (user != null) {
play.Logger.debug("password hash from db |" + user.getPassword() +"|");
Boolean checkPassword = BCrypt.checkpw(password.trim(), user.getPassword());
play.Logger.debug("checkPassword " + checkPassword);
if (checkPassword) {               
return user;
} else {
return null;
}
}
}

运行的相关调试输出

In setPassword part
[debug] application - setPassword |password|
in authenticate part
[debug] application - authenticate password entered |password|
[debug] application - password hash from db |$2a$10$EiuMUWfbCoO.A1GxKk9YeOhqtK0bn4O8Y/W9U/7bEN/CSObOm6jUa|
[debug] application - checkPassword false

这样做的原因是 setPassword 不是进行哈希处理的正确位置,我一直得到一个空白的哈希pw。这曾经在早期版本的游戏中有效,但显然不再有效

我将其移动到@PrePersist方法,如下所示:

@PrePersist
public void hashPassword(){
play.Logger.debug("hashPassword |" + this.password +"|");
String hashed = BCrypt.hashpw(this.password, BCrypt.gensalt(15));
play.Logger.debug("hashed " + hashed);
this.password = hashed;
}

问题已解决

最新更新