结合哈希密码Node.JS时出现PBKDF2错误

binding.PBKDF2 error when hashing passwords Node.JS

本文关键字:PBKDF2 错误 JS 哈希 密码 Node 结合      更新时间:2023-09-26

我正试图用crypto.PBKDF2在用户模型中散列我的密码,但我的validatePassword方法失败,出现以下异常

返回绑定。PBKDF2(密码、salt、迭代、keylen、摘要、回调);

这是全错误

crypto.js:562
return binding.PBKDF2(password, salt, iterations, keylen, digest, callback);
               ^
TypeError: Not a buffer
    at TypeError (native)
    at pbkdf2 (crypto.js:562:20)
    at Object.exports.pbkdf2Sync (crypto.js:553:10)
    at new <anonymous> (c:'Users'Joseph'news-trends'models'Users.js:25:23)
    at Object.<anonymous> (c:'Users'Joseph'news-trends'models'Users.js:24:39)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (c:'Users'Joseph'news-trends'app.js:17:1)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)

以下是的相关方法

UserSchema.methods.setPassword = function(password){
    var self = this;
    crypto.randomBytes(16, function(err, salt){
        if(err){ throw err; }
        self.salt = salt.toString('hex');
    });
    crypto.pbkdf2(password, this.salt, 1000, 64, function(err, hash){
        if(err){ throw err;}
        self.hash = hash.toString('hex');
    });
};
UserSchema.methods.validatePassword = new function(password){
    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
    return this.hash = hash;
};

以下是完整代码的链接:Repo

我知道已经晚了,但如果有人仍然面临这个问题,这就是我所做的,它解决了我的问题。

UserSchema.methods.setPassword = function(password){
    this.salt = crypto.randomBytes(16).toString('hex');
    this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
}
UserSchema.methods.validatePassword = function(password){
    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
    return this.hash === hash;
};

您的代码有些混乱,它将一个变量设置为异步函数,并试图在函数中使用它?

crypto方法有一个回调,其中生成的密钥是第二个参数,这就是通常使用它们的方式

UserSchema.methods.setPassword = function(password){
    var self = this;
    crypto.randomBytes(16, function(err, salt){
        if(err){ throw err; }
        self.salt = salt.toString('hex');
    });
    crypto.pbkdf2(password, this.salt, 1000, 64, function(err, hash){
        if(err){ throw err;}
        self.hash = hash.toString('hex');
    });
}
UserSchema.methods.validatePassword = function(password){
    var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
    return this.hash === hash;
};

请注意,您的setPasswordvalidatePassword方法只适用于一个实例,这可能适合测试,但如果您想要多个用户,则可能需要一个数据库来保存这些值,而不仅仅是将它们分配给this

您得到的错误是因为您试图将异步函数返回的结果传递给new Buffer,而不是生成的密钥