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

# 哈希密码

使用 `Bun.password.hash()` 安全地哈希密码。它内置于 Bun，无需第三方依赖。

```ts theme={null}
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/...
```

***

默认情况下，`Bun.password.hash()` 使用 [Argon2id](https://en.wikipedia.org/wiki/Argon2) 算法。传入第二个参数以使用不同的算法或配置哈希参数。

```ts theme={null}
const password = "super-secure-pa$$word";

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

***

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

```ts theme={null}
// 使用 bcrypt
const bcryptHash = await Bun.password.hash(password, {
  algorithm: "bcrypt",
  cost: 4, // 4-31 之间的数字
});
```

***

使用 `Bun.password.verify()` 验证密码。哈希值中存储了算法及其参数，因此无需再次指定。

```ts theme={null}
const password = "super-secure-pa$$word";
const hash = await Bun.password.hash(password);

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

***

参见 [`Bun.password`](/runtime/hashing#bun-password)。
