API keys, session tokens, and signing secrets are all just random values that must be impossible to guess. Generating them well is straightforward, but a few common shortcuts, such as using a weak random function, undermine everything.
How much randomness do you need?
Aim for at least 128 bits of entropy, and 256 bits (32 random bytes) is a comfortable default for long-lived secrets. That is far beyond what can be brute-forced.
- 16 bytes = 128 bits: 32 hex characters, or 22 base64url characters.
- 32 bytes = 256 bits: 64 hex characters, or 43 base64url characters.
Use a cryptographically secure generator
// Node.js
require("crypto").randomBytes(32).toString("hex")
// Browser
const a = new Uint8Array(32); crypto.getRandomValues(a);
# Python
import secrets; secrets.token_urlsafe(32)
# Shell
openssl rand -hex 32Encoding and format
- Hex is simple and safe everywhere but longer.
- Base64url packs more entropy per character and is safe in URLs and headers.
- A readable prefix (like sk_live_ or ghp_) helps people and scanners recognize a key and tell environments apart. The prefix isn't part of the secret's strength.
- Consider including a short key ID separate from the secret so you can look keys up without storing the secret itself.
Storing and handling keys
- 1Show the full key to the user only once, at creation.
- 2Store only a hash of the key on the server (a fast hash like SHA-256 is fine for high-entropy random keys, unlike passwords).
- 3Compare using a constant-time comparison to avoid timing leaks.
- 4Keep secrets out of source control, client-side code, and logs; use environment variables or a secrets manager.
- 5Support rotation and revocation: keys should be replaceable and expire when appropriate.
If a key leaks
Revoke it immediately, issue a new one, and review access logs for misuse. Removing it from a public repository after the fact doesn't un-leak it.
When you generate keys with an online tool, choose one that creates them in your browser using the Web Crypto API so the value is never transmitted.
Frequently asked questions
+How long should an API key be?
At least 128 bits of randomness; 32 random bytes (256 bits) is a strong default.
+Is Math.random() safe for generating secrets?
No. Use a cryptographically secure generator such as crypto.randomBytes or crypto.getRandomValues.
+Should I store API keys in plain text?
No. Store only a hash of the key and show the full value once when it is created.
+What should I do if an API key is exposed?
Revoke and rotate it immediately, then check logs for unauthorized use.
Secret/API Key Generator
Free, runs in your browser — nothing you enter is uploaded.