# Web Crypto API 参考

URL: https://caijiao.org/reference/web-api/web-crypto
Source: docs/reference/web-api/web-crypto.md
Description: Web Crypto API Reference，整理 crypto.randomUUID、crypto.subtle.digest、SHA 哈希、HTTPS 限制、示例和常见错误。

Web Crypto API 提供浏览器内置的密码学能力，例如安全随机数、UUID、哈希摘要、签名、加密和密钥处理。常见开发场景里，最容易直接用到的是 `crypto.randomUUID()` 和 `crypto.subtle.digest()`。

## 常用能力

| API | 用途 | 返回值 |
| --- | --- | --- |
| `crypto.randomUUID()` | 生成 UUID v4 | 36 位 UUID 字符串 |
| `crypto.getRandomValues()` | 填充安全随机字节 | 传入的 TypedArray |
| `crypto.subtle.digest()` | 计算 SHA 摘要 | `Promise<ArrayBuffer>` |
| `crypto.subtle.sign()` | 签名或 HMAC | `Promise<ArrayBuffer>` |

## 生成 UUID

```js
const id = crypto.randomUUID();
console.log(id);
```

`randomUUID()` 适合生成请求 ID、测试数据 ID、本地临时标识。它不是登录令牌或 API Key 的完整设计方案，安全凭证还需要过期时间、存储策略和服务端校验。

## 计算 SHA-256 哈希

```js
async function sha256(text) {
  const bytes = new TextEncoder().encode(text);
  const buffer = await crypto.subtle.digest("SHA-256", bytes);
  return Array.from(new Uint8Array(buffer), (byte) =>
    byte.toString(16).padStart(2, "0")
  ).join("");
}

console.log(await sha256("caijiao.org"));
```

## digest 支持的算法

| 算法 | 说明 |
| --- | --- |
| `SHA-1` | 旧系统兼容，不建议用于安全场景 |
| `SHA-256` | 常用摘要算法 |
| `SHA-384` | 更长摘要 |
| `SHA-512` | 更长摘要 |

## 常见错误

- Web Crypto 多数能力只在 HTTPS 等安全上下文中可用；本地开发的 `localhost` 通常可以使用。
- `crypto.subtle.digest()` 不能流式处理超大文件，必须先把输入读入内存。
- 哈希不是加密，不能从哈希值还原原文。
- SHA-1 已不适合安全场景；新代码优先使用 SHA-256 或更高版本。
- 需要 HMAC 时不要只拼接字符串再哈希，应使用 `crypto.subtle.sign()` 搭配 HMAC 密钥。

## 相关内容

- [Web API Reference](/reference/web-api/)
- [Blob 参考](/reference/web-api/blob)
- [Hash Generator](/tool/hash-generator)
- [UUID Generator](/tool/uuid-generator)
- [浏览器如何生成 UUID](/how-to/javascript/uuid-browser)
- [MDN Web Crypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API)
- [MDN SubtleCrypto.digest](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest)
- [MDN Crypto.randomUUID](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID)
