パスワードハッシュに bcrypt を使う方法
bcrypt でパスワードを安全にハッシュします。ソルトの生成とコストファクタの調整方法も扱います。
问题
データベースが漏えいした場合でもパスワードが復元されないよう、ユーザーのパスワードを安全に保存する必要があります。
前提条件
- ハッシングと暗号化の違いの理解
- ソルトとコストファクタに関する知識
ステップ
-
1. Choose a cost factor
The bcrypt cost factor determines how many iterations the hashing runs. A cost of 10 takes about 100ms; each increment doubles the time. Choose the highest cost your server can afford during login (typically 10-12).
入力cost: 12输出~400ms per hash -
2. Hash the password with a generated salt
bcrypt automatically generates a random salt and embeds it in the hash. You do not need to manage the salt separately. The output is a single string containing the algorithm, cost, salt, and hash.
入力password: 'correct horse'输出$2b$12$...salt+hash... -
3. Verify on login
To check a password, pass the candidate password and the stored bcrypt hash to the verify function. It extracts the salt and cost from the hash and re-computes, then compares the result. Never compare hashes manually with ==.
入力candidate + stored hash输出true / false
期待される結果
平文を保存せずにパスワードを検証できる、ワークファクター調整可能な bcrypt ハッシュ文字列。
よくあるエラー
- Cost factor too low
- A cost below 10 is too fast for modern hardware. Increase to at least 10-12 to resist GPU brute force.
- Using a fixed salt
- Let bcrypt generate a random salt per password. A fixed salt enables precomputation attacks like rainbow tables.
トラブルシューティング指引
- If hashing is too slow, lower the cost by 1. If too fast, raise it.
- If verify always returns false, check that you are passing the full bcrypt hash string, not just the hash portion.
セキュリティ上の制限
- bcrypt has a 72-byte password limit; longer passwords are truncated. Pre-hash with SHA-256 if you need to support longer passwords.
- All hashing is done locally; no password leaves your browser.