Bun.password.hash() 関数は、Bun で安全にパスワードをハッシュ化するための高速な組み込みメカニズムを提供します。サードパーティの依存関係は不要です。
ts
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);
// => $argon2id$v=19$m=65536,t=2,p=1$tFq+9AVr1bfPxQdh6E8DQRhEXg/M/...デフォルトでは、Argon2id アルゴリズムを使用します。別のアルゴリズムを使用するかハッシュ化パラメータを設定するには、Bun.password.hash() に第 2 引数を渡します。
ts
const password = "super-secure-pa$$word";
// argon2 を使用(デフォルト)
const argonHash = await Bun.password.hash(password, {
memoryCost: 4, // メモリ使用量(キビバイト)
timeCost: 3, // 反復回数
});Bun は bcrypt アルゴリズムも実装しています。これを使用するには algorithm: "bcrypt" を指定します。
ts
// bcrypt を使用
const bcryptHash = await Bun.password.hash(password, {
algorithm: "bcrypt",
cost: 4, // 4-31 の間の数値
});Bun.password.verify() を使用してパスワードを検証します。アルゴリズムとそのパラメータはハッシュ自体に格納されているため、設定を再指定する必要はありません。
ts
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);
const isMatch = await Bun.password.verify(password, hash);
// => true完全なドキュメントについては、ドキュメント > API > ハッシュ化 を参照してください。