了解如何使用bcrypt库在JavaScript中散列和检查密码
bcrypt npm包是在JavaScript中处理密码的最常用的包之一。
这是安全常识,但对于新的开发者来说,值得一提的是:你永远不会将密码以纯文本形式存储在数据库或任何其他地方。你就是不这样做。
你要做的是,从密码中生成一个哈希值,并将其存储起来。
以这种方式。
import bcrypt from 'bcrypt'
// or
// const bcrypt = require('bcrypt')
const password = 'oe3im3io2r3o2'
const rounds = 10
bcrypt.hash(password, rounds, (err, hash) => {
if (err) {
console.error(err)
return
}
console.log(hash)
})
你传递一个数字作为第二个参数,这个数字越大,哈希值就越安全。但也需要更长的时间来生成它。
库的README告诉我们,在一个2GHz的核心上我们可以生成。
rounds=8 : ~40 hashes/sec
rounds=9 : ~20 hashes/sec
rounds=10: ~10 hashes/sec
rounds=11: ~5 hashes/sec
rounds=12: 2-3 hashes/sec
rounds=13: ~1 sec/hash
rounds=14: ~1.5 sec/hash
rounds=15: ~3 sec/hash
rounds=25: ~1 hour/hash
rounds=31: 2-3 days/hash
如果你多次运行bcrypt.hash() ,结果会不断变化。这是关键,因为没有办法从哈希值中重建原始密码。
给定相同的密码和哈希值,就有可能通过bcrypt.compare() 函数找出哈希值是否是由该密码建立的。
bcrypt.compare(password, hash, (err, res) => {
if (err) {
console.error(err)
return
}
console.log(res) //true or false
})
如果是的话,密码与哈希值相匹配,例如,我们可以让用户成功登录。
你也可以使用bcrypt 库中的基于承诺的API,而不是回调。
const hashPassword = async () => {
const hash = await bcrypt.hash(password, rounds)
console.log(hash)
console.log(await bcrypt.compare(password, hash))
}
hashPassword()
看看这个Glitch中的几个例子。