> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 密码哈希

`Bun.password.hash()` 函数提供了一个快速、内置的机制，用于在 Bun 中安全地对密码进行哈希。无需任何第三方依赖。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
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](https://en.wikipedia.org/wiki/Argon2) 算法。传入第二个参数到 `Bun.password.hash()` 可以使用不同的算法或配置哈希参数。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
const password = "super-secure-pa$$word";

// 使用 argon2（默认）
const argonHash = await Bun.password.hash(password, {
  algorithm: "argon2id",
  memoryCost: 8, // 内存使用量，单位为 kibibytes（最小值 8）
  timeCost: 3, // 迭代次数
});
```

***

Bun 还实现了 [bcrypt](https://en.wikipedia.org/wiki/Bcrypt) 算法。指定 `algorithm: "bcrypt"` 即可使用。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
// 使用 bcrypt
const bcryptHash = await Bun.password.hash(password, {
  algorithm: "bcrypt",
  cost: 4, // 数值范围为 4-31
});
```

***

使用 `Bun.password.verify()` 来验证密码。算法及其参数都存储在哈希本身中，因此无须重新指定配置。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);

const isMatch = await Bun.password.verify(password, hash);
// => true
```

***

完整文档请参见 [文档 > API > 哈希](/runtime/hashing#bun-password)。
