繁体   English   中英

NodeJS 卡在 cryto.pbkdf2Sync function

[英]NodeJS stuck at cryto.pbkdf2Sync function

因此,我在 MEAN Stack 应用程序中使用随机盐字符串和密码字符串生成密码 hash。 程序成功生成随机盐并在控制台上打印出来。 但是,它卡在 pbkdf2Sync function 并且无法继续前进。

这是我的代码:

const crypto = require('crypto');

UserSchema.methods.setPassword = function(password){
  console.log('start');
  this.salt = crypto.randomBytes(16).toString('hex');
  console.log(this.salt);
  this.hash = crypto.pbkdf2Sync(new Buffer.alloc(password),  new Buffer.alloc(this.salt), 1000, 64, 'sha512').toString('hex');
  console.log(this.hash);
};

output 结果:

start
ac09ae82b1fbb5b01257b5fa72bfc8614

然后程序就卡在这里了。

据我所知,function 没有被弃用。 我应该如何进行

const crypto = require('crypto');

const hash = (password) => {
  console.log('start');
  const salt = crypto.randomBytes(16).toString('hex');
  console.log(salt);
  const hash = crypto
    .pbkdf2Sync(
      new Buffer.alloc(password.length),
      new Buffer.alloc(salt.length),
      1000,
      64,
      'sha512'
    )
    .toString('hex');
  console.log(hash);
};

hash('hello world');

这对我有用,基本上alloc正在寻找字节数(在内存中分配的大小),字符串在这里不起作用。

如果您希望使用passwordsalt作为填充缓冲区(带值),则使用第二个参数( fill ),在密码的情况下: new Buffer.alloc(password.length, password)

相反,使用.length返回字节数(字符串大小),这会生成“正确”的 output:

start
55387a56bd8ff87ac05be698d938ef04
ab3d65e9e6341a924c752a77b8dc6b78f1e6db5d31df7dd0cc534039dd9662a97bcaf0b959fe78248a49859c7952ddb25d66840f052b27ef1ab60b9446c0c9fd

参考: https://nodejs.org/api/buffer.html#buffer_class_method_buffer_alloc_size_fill_encoding

暂无
暂无

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

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