getRandomValues Fills Typed Arrays With Entropy

crypto.getRandomValues fills typed arrays from a cryptographically secure source, throws QuotaExceededError past 65536 bytes, and suits tokens and sampling.

JavascriptSecurity Boundaries

Code

javascriptsnippet
20 lines
// 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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How the snippet works

Module-level bindings hold the data — bytes, again — with no function scope in between.

What to watch for

  • Uses crypto, so it needs a browser context — it will not run as-is in Node without shims.

Applying it

The demo output is labeled (random hex:, distinct draws:, over quota:), so every printed line maps back to its originating operation.

Statements that matter

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

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `bytes`, `again`.