node.js - Node.js 中的密码哈希

标签 node.js

这是我当前用于密码散列并保存到数据库的代码:

var config = {
  hashBytes: 64,
  saltBytes: 64,
  iterations: 8000
};

crypto.randomBytes(config.saltBytes, function(err, salt) {

  crypto.pbkdf2(password, salt, config.iterations, config.hashBytes,
      function(err, hash) {

          var combined = new Buffer(hash.length + salt.length + 8);

          combined.writeUInt32BE(salt.length, 0, true);
          combined.writeUInt32BE(config.iterations, 4, true);
          salt.copy(combined, 8);
          hash.copy(combined, salt.length + 8);

          callback(combined);
      });
  });

该代码的目标是将 salt 与哈希值一起保存到数据库中的一个字段。这是将密码/盐存储在数据库中同一字段中的可接受的方式吗?我很久以前就发现了这个算法,现在我不确定我是否理解得很好。

据我了解,首先我们创建一个缓冲区,它有足够的空间来存储哈希、盐、迭代次数和盐长度(不知道为什么我们在这里添加 8):

var combined = new Buffer(hash.length + salt.length + 8); 

然后我们将盐长度字节保存到位置0:

combined.writeUInt32BE(salt.length, 0, true);

我们将迭代保存在位置 4(为什么是 4?):

combined.writeUInt32BE(config.iterations, 4, true);

我们将盐保存到位置 8:

salt.copy(combined, 8);

我们将哈希值保存到位置,该位置是盐的长度加上我们保存迭代的大小和盐长度:

hash.copy(combined, salt.length + 8);

最佳答案

使用库bcrypt很容易生成密码哈希。

安装并包含

npm install --save bcrypt

然后包含库

const bcrypt = require( 'bcrypt' );

生成并验证哈希

要以异步方式生成哈希,请使用以下方法。

bcrypt.hash( 'passwordToHash', 10, function( err, hash ) {
  // Store hash in database
});

10 是生成盐时使用的轮数。 验证密码

bcrypt.compare( 'passwordToCompare', hash, function( err, res ) {
  if( res ) {
   // Password matched
  } else {
   // Password didn't match
  } 
});

生成并验证哈希

要以同步方式生成和验证哈希,请使用以下方法。

let hash = bcrypt.hashSync( 'passwordToHash', 10 );

10 是生成盐时使用的轮数。验证哈希

if( bcrypt.compareSync( 'passwordToCompare', hash ) ) {
   // Password matched
} else {
   // Password didn't match
}

关于node.js - Node.js 中的密码哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38045033/

相关文章:

javascript - 在 ReactJS 中导入/导出子组件错误

javascript - 如何在 Node.JS 和客户端 JS 中重复使用相同的类定义?

node.js - NodeJS + Nginx + Cloudflare

javascript - 如何在 nodejs 中处理多个 web3 事务

javascript - 使用 socket.io 发送确认,说我的函数未定义

javascript - 重复时如何从数组中删除 *some* 项? (首选 Lodash/Underscore)

node.js - 如何从 Nodejs 应用程序连接到 Heroku 上的 PostgresQL?

javascript - Node.JS - filter() 仅在索引中进行硬编码时才起作用

javascript - 从 github 执行示例时,Uglify JS API 抛出 TypeError

javascript - 在 Node.js 的 while 循环内使用 setTimeout