bcrypt库_如何使用JavaScript bcrypt库

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:

在此故障中检查几个示例:

翻译自: https://flaviocopes.com/javascript-bcrypt/

bcrypt库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值