← 中文资源

简体中文版本

getRandomValues 给类型化数组填加密熵

crypto.getRandomValues 用加密级随机源填充 TypedArray:超过 65536 字节抛 QuotaExceededError,两次调用结果互异,原地填充可复用,适合令牌与抽样。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

random hex: b237147bc3767b0e
distinct draws: true
over quota: QuotaExceededError
refilled length: 8

实现说明

顶层就这几处状态:bytes、again。

使用要点

  • 用到了 crypto,需要在浏览器环境运行,Node 里直接跑会缺 API。
  • 每一步打印都带着自己的标签:random hex:、distinct draws:、over quota:。

常见问题

安装包是准备工作的一部分吗?

不需要。只用内建 API,安装这一步可以省掉。 文件用顶层绑定保存自己的状态:bytes、again。

核心语句

crypto.getRandomValues(new Uint8Array(65537));
const bytes = new Uint8Array(8);
const again = new Uint8Array(8);

代码示例

// getRandomValues fills a TypedArray from a cryptographically secure source: raw material for tokens, sampling, idempotency keys
const bytes = new Uint8Array(8);
crypto.getRandomValues(bytes);
console.log('random hex:', [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''));

// Two calls never match (collisions in a 128-bit space are negligible)
const again = new Uint8Array(8);
crypto.getRandomValues(again);
console.log('distinct draws:', bytes.join() !== again.join());

// 65536 bytes per call: beyond that QuotaExceededError throws, so batch large fills
try {
  crypto.getRandomValues(new Uint8Array(65537));
} catch (err) {
  console.log('over quota:', err.name);
}

// Filling is in-place: reuse the same array instead of allocating each time
crypto.getRandomValues(bytes);
console.log('refilled length:', bytes.length);