Every system has secrets: API keys, session tokens, HMAC signing keys, password-reset links, JWT signing secrets. The security of all of them rests on one property: an attacker cannot guess them. That property comes entirely from how the secret was generated.
This guide covers what makes a random value safe to use as a secret, what to avoid, and how to size and encode it.
Random is not the same as unpredictable
Most programming languages ship two kinds of random number generator:
- A general-purpose PRNG (
Math.random()in JavaScript,randomin Python,rand()in C). It is fast and produces numbers that look random, which is fine for shuffling a playlist or placing particles on a screen. - A cryptographically secure PRNG (CSPRNG), seeded from operating-system entropy, designed so that observing past output tells you nothing about future output.
General-purpose generators are deterministic. Given a few outputs, an attacker can often reconstruct the internal state and predict everything that follows. V8's Math.random() uses xorshift128+, whose state can be recovered from a handful of consecutive outputs. If your reset tokens come from it, an attacker who requests a few tokens for their own account can predict the ones issued to other users.
Rule: if a value protects anything, it must come from a CSPRNG.
Use the platform's CSPRNG
| Environment | Secure source |
|---|---|
| Browser / Deno / Cloudflare Workers | crypto.getRandomValues() |
| Node.js | crypto.randomBytes() or crypto.randomUUID() |
| Python | secrets.token_bytes(), secrets.token_urlsafe() (not random) |
| Go | crypto/rand (not math/rand) |
| Java | SecureRandom |
| Linux shell | openssl rand or /dev/urandom |
Examples:
// Browser or Node 19+
const bytes = crypto.getRandomValues(new Uint8Array(32)); // 256 bitsopenssl rand -base64 32import secrets
secrets.token_urlsafe(32)How long should a secret be?
Length is measured in bits of entropy, meaning the number of equally likely values an attacker has to search. A 128-bit secret has 2^128 possibilities, which is far beyond any feasible brute force.
| Use case | Minimum | Recommended |
|---|---|---|
| Session IDs, password-reset tokens | 128 bits (16 bytes) | 128-256 bits |
| API keys | 128 bits | 256 bits (32 bytes) |
| HMAC signing keys (HS256) | 256 bits | 256 bits (match the hash output) |
| AES-256 keys | 256 bits | 256 bits (exactly 32 bytes) |
| Webhook signing secrets | 128 bits | 256 bits |
Counting characters can mislead you. A "32-character" secret is only strong if each character is drawn from a large alphabet uniformly at random:
- 32 hex characters = 128 bits
- 32 Base64 characters = 192 bits
- 32 characters of a human-chosen phrase = often under 40 bits
For tokens, think in bytes of randomness, then encode them. Do not think in characters.
Base64 vs hex
Both encode the same random bytes. They only change how the bytes are written down.
| Hex | Base64 | |
|---|---|---|
| Alphabet | 0-9a-f | A-Za-z0-9+/ (and = padding) |
| Size overhead | 2 characters per byte (100%) | about 1.33 characters per byte (33%) |
| URL-safe | Yes | Only the URL-safe variant (- and _) |
| Readability | Easy to read aloud and compare | Compact, but ambiguous characters (l, I, 0, O) |
A 32-byte secret is 64 characters in hex and 44 in Base64 (43 without padding). Use hex when humans will copy or compare it. Use Base64URL when it goes in URLs, headers, or cookies. Neither adds security. They are just representations.
Common mistakes
1. Using Math.random() or a time-based seed. Even Date.now().toString(36) followed by random digits gives far fewer bits than it appears to.
2. Hashing something guessable. sha256(username + timestamp) looks random but has only as much entropy as the inputs. Hashing does not add randomness.
3. Modulo bias. Mapping random bytes to an alphabet with byte % alphabetLength skews the distribution when 256 is not a multiple of the alphabet size. Use rejection sampling, or stick to Base64 or hex, which map cleanly.
4. Reusing a secret across purposes. One key for JWT signing, webhook verification, and encryption means a leak in one place compromises all of them. Generate separate secrets, or derive them with HKDF.
5. Committing secrets to Git. A secret in version history is compromised even after you delete the file. Load secrets from environment variables or a secrets manager, and rotate any that leaked.
6. Logging them. Tokens in access logs, error trackers, and analytics become a second place to steal them from.
Storing and handling secrets
- Store only a hash of tokens that you just verify. For password-reset links or API keys, keep
SHA-256(token)in the database and show the raw token to the user once. A database leak then does not expose usable tokens. (High-entropy tokens do not need a slow hash like bcrypt, because they cannot be brute-forced.) - Compare in constant time (
crypto.timingSafeEqual) to avoid leaking information through response timing. - Make rotation possible. Support two active keys at once so you can roll without downtime.
- Scope and expire. Reset tokens should be single-use and short-lived.
Key takeaways
- Use your platform's CSPRNG, never
Math.random(). - Size secrets in bytes of randomness: 16 is the floor, 32 is a good default.
- Base64 and hex are just encodings of the same bytes, so pick the one that fits where the secret will travel.
- Hashing, timestamps, and cleverness do not add entropy.
Need one right now? The Secret Generator creates cryptographically secure secrets in Base64 or hex using your browser's crypto.getRandomValues(). Nothing is sent to a server, so the secret exists only on your device.