Managing API Keys and Credentials
1. Generating API Keys
| Property | Value |
| Length | 32+ bytes |
| Entropy source | CSPRNG (/dev/urandom) |
| Encoding | base62, base64url |
| Format | sk_live_abc123... |
| Storage | SHA-256 hash, not plaintext |
Example: Key generation (Java)
SecureRandom rng = new SecureRandom();
byte[] bytes = new byte[32];
rng.nextBytes(bytes);
String key = "sk_live_" + Base64.getUrlEncoder()
.withoutPadding().encodeToString(bytes);
String hash = sha256(key); // store hash only
2. Configuring Key Rotation Policies
| Policy | Recommendation |
| Default rotation | Every 90 days |
| High-privilege keys | Every 30 days |
| Overlap period | 7-14 days dual keys |
| Emergency rotation | On suspected breach |
| Auto-rotation | Secrets Manager integration |
3. Implementing Key Scopes and Permissions
Example: Scoped key config
{
"key_id": "sk_live_abc123",
"scopes": ["read:orders", "write:orders"],
"ip_allowlist": ["10.0.0.0/8"],
"rate_limit": { "rps": 100, "burst": 200 },
"expires_at": "2026-12-31T23:59:59Z"
}
4. Setting Key Expiration
| Key Type | TTL |
| Production | 1 year max |
| Development | 90 days |
| Test/CI | 30 days |
| One-time | 1-24 hours |
| Service account | Bound to cert rotation |
5. Using Key Prefixes and Namespaces
| Prefix | Meaning |
sk_live_ | Secret, production |
sk_test_ | Secret, sandbox |
pk_live_ | Publishable (frontend) |
whsec_ | Webhook signing |
rk_ | Restricted/scoped |
Note: Prefixes enable secret scanning (GitHub, GitLab) to auto-detect leaks.
6. Configuring Key Storage
| Storage | Use |
| Hashed in DB | SHA-256 + first 8 chars displayed |
| Vault/KMS | Master key, derive others |
| Client side | OS keychain, never localStorage |
| Env vars | For services, not code |
7. Implementing Key Revocation
| Trigger | Action |
| User request | Self-service portal |
| Leak detected | Auto-revoke + notify |
| Expiry | Auto-disable |
| Account suspension | Revoke all keys |
8. Setting Up Key Usage Limits
| Limit Type | Example |
| Rate | 1000 req/min |
| Quota | 1M req/month |
| Concurrency | 10 in-flight |
| Bandwidth | 10GB/day egress |
| Endpoint scope | Specific paths only |
9. Using Multiple Keys per Client
| Scenario | Reason |
| Env separation | Dev/staging/prod keys |
| Rotation overlap | Old + new during cutover |
| Service split | One key per microservice |
| Audit isolation | Per-CI-job key |
10. Configuring Key Validation
Example: Key validation flow
public ValidationResult validate(String apiKey) {
if (apiKey == null || !apiKey.startsWith("sk_")) return INVALID_FORMAT;
String hash = sha256(apiKey);
Key key = repo.findByHash(hash).orElse(null);
if (key == null) return NOT_FOUND;
if (key.isRevoked()) return REVOKED;
if (key.getExpiresAt().isBefore(Instant.now())) return EXPIRED;
if (!ipAllowed(key, request.getRemoteAddr())) return IP_BLOCKED;
return new ValidationResult(key);
}