bcrypt库
The bcrypt npm package is one of the most used packages to work with passwords in JavaScript.
bcrypt npm软件包是使用JavaScript中密码最多的软件包之一。
This is security 101, but it’s worth mentioning for new developers: you never store a password in plain text in the database or in any other place. You just don’t.
这是安全性101,但对于新开发人员来说值得一提:您永远不会将密码以纯文本格式存储在数据库或任何其他位置。 你只是没有。
What you do instead is, you generate a hash from the password, and you store that.
相反,您要做的是,根据密码生成一个哈希,然后将其存储起来。
In this way:
通过这种方式:
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)
})
You pass a number as second argument and the bigger that is, the more secure the hash is. But also the longer it takes to generate it.
您将数字作为第二个参数传递,并且数值越大,哈希越安全。 但是,生成它所花费的时间也更长。
The library README tells us that on a 2GHz core we can generate:
库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
If you run bcrypt.hash()
multiple times, the result will keep changing. This is key because there is no way to reconstruct the original password from a hash.
如果多次运行bcrypt.hash()
,结果将不断变化。 这是关键,因为无法从哈希中重建原始密码。
Given the same password and a hash it’s possible to find out if the hash was built from that password, using the bcrypt.compare()
function:
给定相同的密码和哈希,可以使用bcrypt.compare()
函数来确定哈希是否是根据该密码构建的:
bcrypt.compare(password, hash, (err, res) => {
if (err) {
console.error(err)
return
}
console.log(res) //true or false
})
If so, the password matches the hash and for example we can let a user log in successfully.
如果是这样,则密码与哈希匹配,例如,我们可以让用户成功登录。
You can use the bcrypt
library with its promise-based API too, instead of callbacks:
您也可以将bcrypt
库及其基于承诺的API一起使用,而不是使用回调:
const hashPassword = async () => {
const hash = await bcrypt.hash(password, rounds)
console.log(hash)
console.log(await bcrypt.compare(password, hash))
}
hashPassword()
Check a couple examples in this Glitch:
在此故障中检查几个示例:
bcrypt库