这是我当前用于密码散列并保存到数据库的代码:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
该代码的目标是将 salt 与哈希一起保存到数据库中的一个字段中。这是在数据库的同一字段中存储密码/盐的可接受方式吗?我很久以前就发现了这个算法,现在我不确定我是否理解这个算法。
据我了解,首先我们创建一个缓冲区,它有足够的空间来存储哈希、盐、迭代次数和盐长度(不知道为什么我们在这里添加 8):
var combined = new Buffer(hash.length + salt.length + 8);
Run Code Online (Sandbox Code Playgroud)
然后我们将盐长度字节保存到位置 0:
combined.writeUInt32BE(salt.length, 0, true);
Run Code Online (Sandbox Code Playgroud)
我们保存迭代位置 4(为什么是 4?):
combined.writeUInt32BE(config.iterations, 4, true);
Run Code Online (Sandbox Code Playgroud)
我们将盐保存到位置 8:
salt.copy(combined, 8);
Run Code Online (Sandbox Code Playgroud)
我们将哈希保存到位置,它是盐的长度加上我们保存迭代和盐长度的大小:
hash.copy(combined, salt.length + 8);
Run Code Online (Sandbox Code Playgroud)
使用库bcrypt很容易生成密码哈希。
npm install --save bcrypt
Run Code Online (Sandbox Code Playgroud)
然后包含库
const bcrypt = require( 'bcrypt' );
Run Code Online (Sandbox Code Playgroud)
要以异步方式生成哈希,请使用以下方法。
bcrypt.hash( 'passwordToHash', 10, function( err, hash ) {
// Store hash in database
});
Run Code Online (Sandbox Code Playgroud)
10是生成盐时使用的轮数。验证密码
bcrypt.compare( 'passwordToCompare', hash, function( err, res ) {
if( res ) {
// Password matched
} else {
// Password didn't match
}
});
Run Code Online (Sandbox Code Playgroud)
要以同步方式生成和验证哈希,请使用以下方法。
let hash = bcrypt.hashSync( 'passwordToHash', 10 );
Run Code Online (Sandbox Code Playgroud)
10是生成盐时要使用的轮数。验证哈希
if( bcrypt.compareSync( 'passwordToCompare', hash ) ) {
// Password matched
} else {
// Password didn't match
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4625 次 |
| 最近记录: |