我正在尝试添加密码,但是出现以下错误消息:
(节点:958)MaxListenersExceededWarning:可能的事件发射器内存 检测到泄漏。添加了11个出口侦听器。使用generator.setMaxListeners() 增加限制
TypeError:Salt必须是缓冲区
at pbkdf2 (crypto.js:644:20) at Object.exports.pbkdf2 (crypto.js:624:10) at model.exports.UserCredentialsSchema.methods.setPassword (/Users/friso/Documents/projects/MEANpress/server/src/schemas/user-credentials.schema.ts:35:5) at App.setupMongoose (/Users/friso/Documents/projects/MEANpress/server/src/App.ts:42:15) at new App (/Users/friso/Documents/projects/MEANpress/server/src/App.ts:14:14) at Object.<anonymous> (/Users/friso/Documents/projects/MEANpress/server/src/server.ts:5:13) at Module._compile (module.js:635:30) at Module.m._compile (/Users/friso/Documents/projects/MEANpress/server/node_modules/ts-node/src/index.ts:439:23) at Module._extensions..js (module.js:646:10) at Object.require.extensions.(anonymous function) [as .ts] (/Users/friso/Documents/projects/MEANpress/server/node_modules/ts-node/src/index.ts:442:12) at Module.load (module.js:554:32) at tryModuleLoad (module.js:497:12) at Function.Module._load (module.js:489:3) at Function.Module.runMain (module.js:676:10) at Object.<anonymous> (/Users/friso/Documents/projects/MEANpress/server/node_modules/ts-node/src/bin.ts:157:12) at Module._compile (module.js:635:30)
我正在尝试为此模式和方法做
export var UserCredentialsSchema: Schema = new Schema({
username: {
type: String,
lowercase: true,
unique: true
},
password: String,
salt: String
});
UserCredentialsSchema.methods.setPassword = function (password: string): void {
randomBytes(saltLength, (err, buf) => {
console.error(err);
this.salt = buf.toString();
});
pbkdf2(password, this.salt, hashIterations, hashLength, digest, (err, derivedKey) => {
console.error(err);
this.hashedPassword = derivedKey;
});
};
从在线文档和教程中,我了解到crypto会自行将盐的字符串转换为缓冲区,但是此错误使我不以为然。
也许我错过了使用pbkdf2
的任何步骤吗?
尝试在设置中创建管理员用户时出现错误:
const admin = new UserCredentials();
admin.username = 'admin';
admin.setPassword('admin');
admin.save();
链接到Github中的源代码:
答案 0 :(得分:2)
如果您通过回调调用randomBytes
(我假设它是crypto.randomBytes
),则该过程是异步进行的。因此,在调用pbkdf2
时,this.salt
尚未初始化。
将调用移至pbdkf2
'回调内的randomBytes
,或使用隐式同步版本:
try {
this.salt = randomBytes(saltLength);
} catch (err) {
// handle err here
}