🍋
Menu
How-To Beginner 2 min read 300 words

How to Generate Secure API Keys

Create cryptographically secure API keys with proper entropy, formatting, and management practices.

Key Takeaways

  • API keys authenticate applications and services.
  • For security-critical APIs, enforce key expiration (90-365 days) with automated renewal.
  • ### Secure Storage Never embed API keys in source code or client-side applications.

Generating Secure API Keys

API keys authenticate applications and services. A weak or predictable key is equivalent to no authentication. Proper key generation ensures keys are unguessable and resistant to brute-force attacks.

Entropy Requirements

API keys should have at least 128 bits of entropy (16 random bytes). This produces approximately 3.4 × 10^38 possible values — computationally infeasible to brute-force. 256 bits (32 random bytes) is better for long-lived keys. Use the operating system's CSPRNG (cryptographically secure pseudo-random number generator): crypto.getRandomValues() in browsers, /dev/urandom on Linux, CryptGenRandom on Windows.

Encoding and Format

Encode random bytes as hex (32-64 characters) or base64url (22-43 characters). Include a recognizable prefix for the service: pk_live_ for production keys, pk_test_ for test keys. This helps identify keys found in logs and prevents accidentally using test keys in production. Stripe's format (sk_live_...) is a good model.

Key Rotation

All API keys should have a rotation schedule. Offer two active keys simultaneously so applications can rotate without downtime: generate a new key, update the application to use the new key, verify it works, then revoke the old key. For security-critical APIs, enforce key expiration (90-365 days) with automated renewal.

Secure Storage

Never embed API keys in source code or client-side applications. Use environment variables on servers. For mobile apps, use the device's secure storage (Keychain on iOS, Keystore on Android). For CI/CD pipelines, use secret management services. API keys committed to Git repositories should be immediately revoked — the key's history in Git makes it permanently exposed.

Rate Limiting and Monitoring

Associate each API key with rate limits and usage quotas. Monitor for anomalous usage patterns: sudden volume spikes, requests from unexpected IP ranges, or access to unusual endpoints. Alert on failed authentication attempts — they may indicate a brute-force attack.

Related Tools

Related Formats

Related Guides