Codectionary / Developer documentation / JavaScript

Cryptographic Random Values

crypto.getRandomValues fills an integer typed array with cryptographically strong random values. crypto.randomUUID creates a version-4 UUID and requires a secure browser context. Neither a UUID nor a random value automatically supplies authorization or replaces a properly designed security protocol.

Syntax

crypto.getRandomValues(new Uint8Array(16));
crypto.randomUUID();

Examples

Cryptographic Random Values: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: The console prints 16 32 and true; the actual bytes differ on each run.

const bytes = crypto.getRandomValues(new Uint8Array(16));
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
console.log(bytes.length, hex.length);
console.log(/^[0-9a-f]{32}$/.test(hex));
  1. Expected result: The console prints 16 32 and true; the actual bytes differ on each run.
  2. Padding gives every byte exactly two hexadecimal characters.
  3. The test verifies representation length and alphabet, not a particular random result.

Best practices

  • Use this API instead of Math.random for security-sensitive randomness.
  • Avoid biased modulo mapping when choosing uniformly from a range that does not divide the source range.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading