Closed4
Bcryptでパワスワードのハッシュ化と照合を行う
以下のライブラリを用いて、javascriptでパスワードをハッシュ化する方法や、ユーザの入力値とハッシュ化したパスワードを照合する方法を記載。
インストール
npm i bcrypt
パスワードのハッシュ化
基本系
index.js
const bcrypt = require('bcrypt')
const saltRounds = 10;
const rawPassword = "asdfgttlkas5"
bcrypt.hash(rawPassword, saltRounds)
-
saltRounds
: ハッシュ化における計算量を表す。- デフォルトは10
- 10を指定した場合は、2の10乗回、処理される。
ref. What are Salt Rounds and how are Salts stored in Bcrypt?
With "salt round" they actually mean the cost factor. The cost factor controls how much time is needed to calculate a single BCrypt hash. The higher the cost factor, the more hashing rounds are done. Increasing the cost factor by 1 doubles the necessary time.
A cost factor of 10 means that the calculation is done 2^10 times which is about 1000 times.
- コールバック関数も使える
To hash a password - node.bcrypt.js
関数内での実行
asyncなので、関数内で実行する場合は、awaitする
const doSomething = async () => {
const hashedPassword = await bcrypt.hash(rawPassword, saltRounds)
// e.g. dbにinsertする
}
パスワードの照合
index.js
const rawPassword = "asdfgttlkas5"
const hash = await bcrypt.hash(rawPassword, saltRounds)
const correctPassword = "asdfgttlkas5"
bcrypt.compre(correctPassword, hash)
// => true
const incorrectPassword = "rkfkgt9rtbs5"
bcrypt.compre(incorrectPassword, hash)
// => false
このスクラップは2023/11/21にクローズされました