Generate API Keys and Secret Tokens
Generate high-entropy API keys and secret tokens for web services. Covers recommended formats, key lengths, base62/base64 encoding, prefix conventions, and secure storage practices.
Detailed Explanation
API Key and Secret Token Generation
API keys and secret tokens serve as machine-to-machine authentication credentials. They require maximum entropy with no memorability constraint, making them ideal candidates for long, fully random strings.
API Key Formats
Different services use different formats:
Hex String (Base16)
a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
- 16 characters of entropy per 32 hex characters
- Common for HMAC secrets and hash-based tokens
Base62 (Alphanumeric)
kR9mT2pX7nQw4bYsHt5vL8jB3eY6cN1x
- URL-safe without encoding
- ~5.95 bits per character
- Widely used for API keys
Base64 / Base64URL
a1B2c3D4+e5F6/a7B8==
a1B2c3D4-e5F6_a7B8
- ~6 bits per character (most efficient)
- Base64URL variant avoids
+,/,=for URL safety
Recommended Key Lengths
| Use Case | Minimum Bits | Format | Length |
|---|---|---|---|
| API key | 128 bits | Base62 | 22 chars |
| HMAC secret | 256 bits | Hex | 64 chars |
| JWT secret | 256 bits | Base64 | 44 chars |
| OAuth client secret | 256 bits | Base62 | 43 chars |
| Webhook signing key | 256 bits | Hex | 64 chars |
Prefix Conventions
Many services add prefixes to identify key types:
sk_live_kR9mT2pX7nQw4bYs (Stripe secret key)
pk_test_Ht5vL8jB3eY6cN1x (Stripe publishable key)
ghp_xxxxxxxxxxxxxxxxxxxx (GitHub personal access token)
Prefixes help with:
- Identification — quickly determine the key type
- Secret scanning — automated detection of leaked keys in code
- Revocation — search logs for specific key patterns
Secure Storage
API keys require strict handling:
- Environment variables — never commit to version control
- Secrets managers — AWS Secrets Manager, GCP Secret Manager, HashiCorp Vault
- Encrypted at rest — keys stored in databases should be encrypted
- Scoped permissions — assign minimum required permissions per key
- Rotation schedule — rotate keys every 90 days or after personnel changes
Generating Keys in Code
Using the Web Crypto API (browser-safe):
const array = new Uint8Array(32);
crypto.getRandomValues(array);
const key = Array.from(array, b =>
b.toString(16).padStart(2, '0')
).join('');
Use Case
API keys and secret tokens are used by developers integrating third-party services, building REST APIs, configuring webhooks, and setting up OAuth applications. Every SaaS product, mobile app backend, and microservice needs securely generated authentication tokens for service-to-service communication.