实现说明
顶层就这几处状态: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);