javascript 节点 bcrypt 的比较总是返回 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14795130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 22:36:00  来源:igfitidea点击:

Node bcrypt's compare always returns false

javascriptnode.jsbcrypt

提问by cmcd

I am stumped trying to get my passwords to successfully compare with bcrypt using node. Maybe I missed something, but on account creation, I do the following within the signup method (with some code abbreviated):

我很难让我的密码成功地与使用 node.js 的 bcrypt 进行比较。也许我错过了一些东西,但在创建帐户时,我在注册方法中执行以下操作(一些代码缩写):

bcrypt.genSalt(10, function(err, salt) {
               if(err) {

               }
               bcrypt.hash(user.Password, salt, function(err, hash) {
                           console.log('hashing and saving');
                           db.query(db insert code, function (error, rows, fields) {
                                    if(error) {
                                    console.log(error);
                                    res.setHeader('500', { 'Content-Type': 'x-application/json'});
                                    res.send({UserId: 0, ErrorMessage: 'Something terrible happened.'});
                                    } else {
                                    console.log('User created : ' + rows.insertId);
                                    res.setHeader('200', { 'Content-Type': 'x-application/json'});
                                    res.send({UserId: rows.insertId});
                                    }
                                    });
                           });
               });

return next();

This all works fine. My db has the encrypted password. But when a user signs in, I cannot get a successful result from bcrypt.compare:

这一切正常。我的数据库有加密密码。但是当用户登录时,我无法从 bcrypt.compare 获得成功的结果:

db.query(get account code, function(error, rows, fields) {
         if(rows.length == 1) {
           bcrypt.compare(request.params.password, rows[0].Password, function(err,res) {
              if(err) { console.log(err.toString()); }
              if(res == true)
              {
                        response.setHeader('200', { 'Content-Type': 'x-application/json' });
                        response.send({result: true});
              } else {
                        response.setHeader('401', { 'Content-Type': 'x-application/json' });
                        console.log('invalid password');
                        response.send({result:false});
                     }
              });
         }
        });

return next();

And I always end up with invalid password. Do I need to take the cleartext password and re-encrypt it before comparing to what I pull out of the database?

而且我总是以无效的密码告终。在与我从数据库中提取的内容进行比较之前,我是否需要获取明文密码并重新加密它?

回答by Gal Ben-Haim

you can skip doing bcrypt.genSaltand use bcrypt.hash(password, 10, function(err, hash) {..});

你可以跳过做bcrypt.genSalt和使用bcrypt.hash(password, 10, function(err, hash) {..});

your compare function seems good to me.

你的比较功能对我来说似乎很好。

this is working fine for me:

这对我来说很好用:

var bcrypt = require('bcrypt');

bcrypt.hash('mypassword', 10, function(err, hash) {
    if (err) { throw (err); }

    bcrypt.compare('mypassword', hash, function(err, result) {
        if (err) { throw (err); }
        console.log(result);
    });
});

回答by Ernesto

I dont know if you have the same as I did, I had the same problem because my table had the length of 45 chars and I bcrypt compares if the hash lenght is diferent from 60 it returns false. Just increase the length of characters in your table

我不知道你是否和我一样,我遇到了同样的问题,因为我的表有 45 个字符的长度,我 bcrypt 比较哈希长度是否与 60 不同,它返回 false。只需增加表格中字符的长度

回答by Ross Reicks

Mine was due to my database column not having a large enough varchar length. A good place to check.

我的原因是我的数据库列没有足够大的 varchar 长度。检查的好地方。

回答by GCH

Just modify the length of characters in your database assign to password field, maybe the hash generated is more larger than the field can support

只需修改数据库中分配给密码字段的字符长度,可能生成的哈希值大于该字段所能支持的

回答by ThreeCheeseHigh

I had the same problem. After changing the node package from bcryptto bcryptjsthe comparision worked like a charm. Since the package seems to be a fork, the functions do not need to be adjusted.

我有同样的问题。将节点包从bcrypt更改bcryptjs为比较后,效果非常好。由于包似乎是一个fork,所以不需要调整功能。

回答by henrip

I had the same issue and for me the solution was to fix a typo in my frontend. I was sending 'pasword' from my form and expecting 'password'. Somehow bcyppt then hashed the returned undefined value and that was the reason compare() always returned false.

我遇到了同样的问题,对我来说,解决方案是修复前端的拼写错误。我正在从我的表单发送“密码”并期待“密码”。不知何故 bcyppt 然后散列返回的未定义值,这就是 compare() 总是返回 false 的原因。

Hope this helps someone!

希望这对某人有帮助!

回答by zero.zero.seven

my hash was starting with $2y and it had to start with $2b

我的哈希从 $2y 开始,它必须从 $2b 开始

This library supports $2a$ and $2b$ prefix bcrypt hashes. $2x$ and $2y$ hashes are specific to bcrypt implementation developed for John the Ripper. In theory, they should be compatible with $2b$ prefix.

这个库支持 $2a$ 和 $2b$ 前缀 bcrypt 哈希。$2x$ 和 $2y$ 哈希特定于为 John the Ripper 开发的 bcrypt 实现。理论上,它们应该与 $2b$ 前缀兼容。

回答by sushilprj

This works for me.

这对我有用。

var bcrypt = require('bcrypt');
var salt = bcrypt.genSaltSync();

bcrypt.hash('mypassword', salt, function(err, hash){
    if(err) throw err;

    bcrypt.compare('mypassword', hash, function(err, result) {
      if (err) { throw (err); }
      console.log(result);
    });

});

回答by Francesco

I had this same problem, but I am sure I am not encoding my password twice. Here is the thing. bcrypt-nodejs npm package is on v0.0.3 and I am using this version. I am writing the algorithm to store a user password on register and read a user password on login. The frontend is a simple with input text for email field and input password for password field. When I submit the request I POST a call to https://localhost... on my local node server. I can log the data received and I can see the password logged is the same as the password inserted on frontend.

我遇到了同样的问题,但我确定我没有对密码进行两次编码。这是事情。bcrypt-nodejs npm 包在 v0.0.3 上,我正在使用这个版本。我正在编写算法以在注册时存储用户密码并在登录时读取用户密码。前端是一个简单的电子邮件字段输入文本和密码字段输入密码。当我提交请求时,我会在本地节点服务器上发布对https://localhost...的调用。我可以记录收到的数据,我可以看到记录的密码与前端插入的密码相同。

The code used to store the password is:

用于存储密码的代码是:

//var user.bcrypt = bcrypt.genSaltSync(10);;
var clearPwd = user.password;
user.password = bcrypt.hashSync(clearPwd);//, user.bcrypt);
log4.debug("hashSyncked: "+ user.password);
db.userSave(user, cb);

The code used to read and compare password is:

用于读取和比较密码的代码是:

log4.debug('compare '+pwd+' with saved on db for user %j', userDoc.password);
var okPwd = bcrypt.compareSync(pwd, userDoc.password);

So, I see the hashed password, it is logged as a string like $ert3435tF.02ri etc...

所以,我看到了散列密码,它被记录为一个字符串,如 $ert3435tF.02ri 等......

But everytime I login with the same password I registered with, okPwdis always false. Why?

但是每次我使用注册时使用的相同密码登录时,okPwd总是错误的。为什么?

Even if I un-comment the commented code!

即使我取消注释注释代码!

UPDATEThe solution I found was about methods. Password should not be stored and read like that, it is too ...rude !! The correct method is mentioned hereWatch out! There is an error in that guideline. bcrypt.hash(...) functions needs 2 object parameter and 2 callbacks! The last one is the one called at the end of the hash process, the first is called to track the hash proces. I put that a nulland it all works well. I admit I made another mistake: I used bcrypt-nodejs package instead of brcrypt.

更新我找到的解决方案是关于方法的。密码不应该那样存储和读取,这太......粗鲁了!!这里提到正确的方法当心!该指南中存在错误。bcrypt.hash(...) 函数需要 2 个对象参数和 2 个回调!最后一个是在散列过程结束时调用的,第一个用于跟踪散列过程。我把它设为空值,一切正常。我承认我犯了另一个错误:我使用了 bcrypt-nodejs 包而不是 brcrypt。