Generate cryptographically secure random values in your browser
Whether you need a session secret, a CSRF token, an encryption key, or a reproducible-looking test fixture, you want randomness from a cryptographically strong source — not Math.random. This generator uses the Web Crypto API directly, produces between 8 and 512 bytes, and encodes them in whichever format your code expects.
How it works
The tool allocates a Uint8Array of the requested length and fills it with crypto.getRandomValues(), the browser’s CSPRNG. The raw bytes are then encoded:
- Hex / HEX — each byte becomes two hex characters (
toString(16)padded to 2), lower or upper case. - Base64 / Base64URL — the bytes are turned into a binary string and passed to
btoa; the URL-safe variant swaps+//for-/_and strips=padding. - Decimal — the bytes are read big-endian into a
BigIntso even 512-byte values convert exactly with no floating-point loss.
The byte count is clamped to the 8–512 range, and the tool falls back to a clear message if Web Crypto is unavailable.
Choosing the right size and format
| Use case | Recommended bytes | Format |
|---|---|---|
| Session ID / cookie | 32 | hex or base64url |
| CSRF token | 32 | hex or base64url |
| AES-256 key | 32 | hex or base64 |
| AES-128 key | 16 | hex or base64 |
| API key (URL-safe) | 32 | base64url |
| Nonce / IV | 16 | hex |
| HMAC secret | 64 | hex |
For example: a 32-byte base64url token is 43 characters long with no padding, no +, and no / — drop it directly into a URL query parameter or Authorization: Bearer header without any additional encoding step. A 32-byte hex string is 64 lowercase characters, which is easy to copy and store in most databases.
Why Math.random is not safe
Math.random is a pseudo-random number generator seeded at startup; its output can be predicted if an attacker observes enough values. For tokens and secrets this is unacceptable. crypto.getRandomValues draws from the operating system’s entropy pool — physical hardware events, timing jitter, interrupt noise — which an attacker cannot predict or reproduce.
Security hygiene after generating
- Store in a secrets manager or environment variable, never in source code.
- Set an expiry on session tokens; rotate API keys on a regular schedule.
- Log a token ID or a hash (never the raw value) for audit trails.
- If a secret is compromised, invalidate it immediately — the generator makes a new one in one click.
- For encryption keys, the format matters: many libraries expect the raw bytes as a
BufferorUint8Array, not a hex string, so check your library’s key-import API before choosing a format.
Everything runs in your browser — the bytes are generated locally and never sent anywhere.