这是我当前用于密码散列并保存到数据库的代码:
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/