简体   繁体   English

节点 bcrypt 的比较总是返回 false

[英]Node bcrypt's compare always returns false

I am stumped trying to get my passwords to successfully compare with bcrypt using node.我很难让我的密码成功地与使用节点的 bcrypt 进行比较。 Maybe I missed something, but on account creation, I do the following within the signup method (with some code abbreviated):也许我错过了一些东西,但在创建帐户时,我在注册方法中执行以下操作(一些代码缩写):

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?在与从数据库中提取的内容进行比较之前,我是否需要获取明文密码并重新加密?

you can skip doing bcrypt.genSalt and 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);
    });
});

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 bcrypt compares if the hash lenght is diferent from 60 it returns false.我不知道你是否有和我一样的问题,我有同样的问题,因为我的表的长度为 45 个字符,bcrypt 比较哈希长度是否与 60 不同,它返回 false。 Just increase the length of characters in your table只需增加表格中字符的长度

Mine was due to my database column not having a large enough varchar length.我的原因是我的数据库列没有足够大的 varchar 长度。 A good place to check.一个检查的好地方。

Arguments for bcrypt's compare method should be bcrypt 的比较方法的参数应该是

bcrypt.compare(actual_password, encrypted_password)

instead of代替

bcrypt.compare(encrypted_password, actual_password)

=> the encrypted_password should be the second argument. => encrypted_pa​​ssword 应该是第二个参数。

For me it was just an arguments disorder对我来说,这只是一种争论障碍

The right order正确的顺序

bcrypt.compare(plainPasswordToCheck, hashedPasswordOnStorage)

I had the same problem.我有同样的问题。 After changing the node package from bcrypt to bcryptjs the comparision worked like a charm.在将节点包从bcrypt更改为bcryptjs ,比较就像一个魅力。 Since the package seems to be a fork, the functions do not need to be adjusted.由于包似乎是一个fork,功能不需要调整。

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. bcrypt-nodejs npm 包在 v0.0.3 上,我正在使用这个版本。 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.当我提交请求时,我在本地节点服务器上发布对https://localhost ... 的调用。 I can log the data received and I can see the password logged is the same as the password inserted on frontend.我可以记录收到的数据,我可以看到记录的密码与前端插入的密码相同。

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, okPwd is always false.但是每次我使用注册时的相同密码登录时, okPwd总是错误的。 Why?为什么?

Even if I un-comment the commented code!即使我取消注释注释代码!

UPDATE The solution I found was about methods.更新我找到的解决方案是关于方法的。 Password should not be stored and read like that, it is too ...rude !!密码不应该这样存储和读取,这太……粗鲁了! The correct method is mentioned here Watch out! 这里提到了正确的方法当心! There is an error in that guideline.该指南有错误。 bcrypt.hash(...) functions needs 2 object parameter and 2 callbacks! bcrypt.hash(...) 函数需要 2 个对象参数和 2 个回调! 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 null and it all works well.我把它设为空,一切都很好。 I admit I made another mistake: I used bcrypt-nodejs package instead of brcrypt.我承认我犯了另一个错误:我使用 bcrypt-nodejs 包而不是 brcrypt。

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

my hash was starting with $2y and it had to start with $2b我的哈希以 $2y 开头,它必须以 $2b 开头

This library supports $2a$ and $2b$ prefix bcrypt hashes.该库支持 $2a$ 和 $2b$ 前缀 bcrypt 哈希。 $2x$ and $2y$ hashes are specific to bcrypt implementation developed for John the Ripper. $2x$ 和 $2y$ 哈希是专门为 John the Ripper 开发的 bcrypt 实现。 In theory, they should be compatible with $2b$ prefix.理论上,它们应该与 $2b$ 前缀兼容。

在比较功能中很容易混淆顺序;)

bcrypt.compare(user_entered_password, database_encrypted_password)

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);
    });

});

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!希望这对某人有帮助!

Another possible solution which worked for me is if in your User model you put under password field.对我有用的另一种可能的解决方案是,如果在您的用户模型中,您将其放在密码字段下。

lowercase: true,

I happened to had this one copied from another field.我碰巧从另一个领域复制了这个。 When I removed it the issue disappeared.当我删除它时,问题就消失了。

I deleted my user and recreated it and did this我删除了我的用户并重新创建了它并这样做了

const isMatch = await bcrypt.compare(password, user.password);
console.log(user.password, isMatch);
if (!isMatch) {
  return res.status(400).json({
    msg:
      "Sorry, your password was incorrect. Please double-check your password.",
  });

and at the time of creating a user, I did this在创建用户时,我这样做了

const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);

In the compare function, you do not need to generate a new hash, do this:在比较函数中,您不需要生成新的哈希,请执行以下操作:

async function Login(email, password) {
  const user = await this.service.getByEmail(email);

  const passwordBd = user.user_password;

  const matching = await bcrypt.compare(password, passwordBd);

  console.log(matching); //true
};

In my case, I was passing in the hash as a command line argument to a node program - just for testing:就我而言,我将哈希作为命令行参数传递给节点程序 - 仅用于测试:

node admin/bcrypt.js password $2b$10$/v9nAxpPQoDH5LMa/q.0AON/gEk.AxF57hHtIGkKR5IAWfMLyBcmm

The hash started with $2b$10$/ ;哈希以$2b$10$/开头; the $2 and $1 were interpreted as positional arguments and evaluated to empty values, hence the value being compared was different than what I passed in. Escaping the $ symbols with a \ solved the issue: $2$1被解释为位置参数并评估为空值,因此被比较的值与我传入的值不同。用\转义$符号解决了这个问题:

node admin/bcrypt.js password \$2b\$10\$/v9nAxpPQoDH5LMa/q.0AON/gEk.AxF57hHtIGkKR5IAWfMLyBcmm

I had the same problem with postgresql, but should always be the same.我对 postgresql 有同样的问题,但应该总是一样的。

I simply had to trim my db result:我只需要修剪我的数据库结果:

bcrypt.compare(
    req.body.password,
    String(user.PASSWORD).trim()
)

i dont know if you have the same as I did, I had the same problem because my table had the length of 35 chars and bcrypt compares if the hash lenght is diferent from 60 it returns false.我不知道你是否和我一样,我有同样的问题,因为我的表有 35 个字符的长度,如果 hash 长度与 60 不同,则 bcrypt 比较它返回 false。 Just increase the length of characters in your table只需增加表格中字符的长度

那是由于密码长度为 45,增加它并解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM