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.
Code
// 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: 8How 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
HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Password Entropy EstimatorEstimate a password's alphabet size and Shannon entropy in bits, then translate that into offline crack times at realistic guessing rates.Password Strength MeterScore a password from 0 to 100 based on length and character classes, and get clear suggestions to make it stronger. Everything runs locally.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.