nodejs pbkdf2sync TypeError:密码短语必须是缓冲区

时间:2018-08-10 10:41:40

标签: angularjs node.js mean-stack cryptojs

我正在研究平均堆栈应用程序。我正在使用加密技术进行密码加密,但是它抛出了错误。

TypeError:密码短语必须是缓冲区

  

TypeError:密码短语必须是缓冲区       在pbkdf2(crypto.js:702:20)       在Object.exports.pbkdf2Sync(crypto.js:687:10)       在model.userSchema.methods.setPassword(C:\ CMT_Platform \ server \ models \ user.model.js:24:24)       在Object.module.exports.register(C:\ CMT_Platform \ server \ services \ auth.service.js:16:13)       在exports.register(C:\ CMT_Platform \ server \ controllers \ auth.controller.js:22:39)       在Layer.handle [作为handle_request](C:\ CMT_Platform \ node_modules \ express \ lib \ router \ layer.js:95:5)       在下一个(C:\ CMT_Platform \ node_modules \ express \ lib \ router \ route.js:137:13)       在Route.dispatch(C:\ CMT_Platform \ node_modules \ express \ lib \ router \ route.js:112:3)       在Layer.handle [作为handle_request](C:\ CMT_Platform \ node_modules \ express \ lib \ router \ layer.js:95:5)       在C:\ CMT_Platform \ node_modules \ express \ lib \ router \ index.js:281:22       在Function.process_params(C:\ CMT_Platform \ node_modules \ express \ lib \ router \ index.js:335:12)       在下一个(C:\ CMT_Platform \ node_modules \ express \ lib \ router \ index.js:275:10)       在Function.handle(C:\ CMT_Platform \ node_modules \ express \ lib \ router \ index.js:174:3)       在路由器上(C:\ CMT_Platform \ node_modules \ express \ lib \ router \ index.js:47:12)       在Layer.handle [作为handle_request](C:\ CMT_Platform \ node_modules \ express \ lib \ router \ layer.js:95:5)       在trim_prefix(C:\ CMT_Platform \ node_modules \ express \ lib \ router \ index.js:317:13):: 1   --[11 / Aug / 2018:08:33:55 +0000]“ POST / register HTTP / 1.1” 400 42“-”“ Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,   例如Gecko)Chrome / 68.0.3440.106 Safari / 537.36“

代码:

var custschema= new mongoose.Schema({
    email: { type: String, unique: true, required: true },
    name: { type: String, required: true },
    role: { type: String },
    hash: String,
    salt: String
});

custschema.methods.setPassword = function(password) {
    this.salt = crypto.randomBytes(16).toString('hex');
    //this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex');
    var buffer = new Buffer(this.salt, "binary");
    console.log(this.salt);
    console.log(buffer);
    this.hash = crypto.pbkdf2Sync(password, buffer, 1000, 64, 'sha512').toString('hex');
};

custschema.methods.validPassword = function(password) {
    //var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha512').toString('hex');
    var hash = crypto.pbkdf2Sync(password, new Buffer(this.salt,'binary'), 1000, 64, 'sha512').toString('hex');
    return this.hash === hash;
};

无论是否遇到此问题,有人可以请我指导或启发我。如果您需要更多详细信息,请告诉我。

谢谢

1 个答案:

答案 0 :(得分:0)

crypto.pbkdf2Sync返回Buffer并且您正在存储在字符串中,或​​者可以将buffer转换为字符串并进行存储。

您可以将hast类型更改为Buffer,然后尝试检查Mongoose数据类型here