Managing API Keys and Credentials

1. Generating API Keys

PropertyValue
Length32+ bytes
Entropy sourceCSPRNG (/dev/urandom)
Encodingbase62, base64url
Formatsk_live_abc123...
StorageSHA-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

PolicyRecommendation
Default rotationEvery 90 days
High-privilege keysEvery 30 days
Overlap period7-14 days dual keys
Emergency rotationOn suspected breach
Auto-rotationSecrets 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 TypeTTL
Production1 year max
Development90 days
Test/CI30 days
One-time1-24 hours
Service accountBound to cert rotation

5. Using Key Prefixes and Namespaces

PrefixMeaning
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

StorageUse
Hashed in DBSHA-256 + first 8 chars displayed
Vault/KMSMaster key, derive others
Client sideOS keychain, never localStorage
Env varsFor services, not code

7. Implementing Key Revocation

TriggerAction
User requestSelf-service portal
Leak detectedAuto-revoke + notify
ExpiryAuto-disable
Account suspensionRevoke all keys

8. Setting Up Key Usage Limits

Limit TypeExample
Rate1000 req/min
Quota1M req/month
Concurrency10 in-flight
Bandwidth10GB/day egress
Endpoint scopeSpecific paths only

9. Using Multiple Keys per Client

ScenarioReason
Env separationDev/staging/prod keys
Rotation overlapOld + new during cutover
Service splitOne key per microservice
Audit isolationPer-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);
}