如何使用JavaScript bcrypt庫

了解如何使用bcrypt庫對JavaScript中的哈希進行哈希處理和檢查密碼

bcrypt npm軟件包是使用JavaScript中密碼最多的軟件包之一。

這是安全性101,但是對於新開發人員來說值得一提:您永遠不會將密碼以純文本格式存儲在數據庫中或任何其他位置。你只是沒有。

相反,您要做的是,根據密碼生成一個哈希,然後將其存儲起來。

這樣:

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

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.

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(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:

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:


More js tutorials: