API keys are the simplest form of authentication — and the most frequently compromised. Keys in GitHub, in the frontend, with no expiration.
Generation¶
import secrets, hashlib def generate_api_key(prefix=”sk”): raw = secrets.token_urlsafe(32) full = f”{prefix}_{raw}” hash = hashlib.sha256(full.encode()).hexdigest() return full, hash # full → to the user ONCE, hash → to DB
Storage¶
API Key Management¶
✅ os.environ[‘STRIPE_API_KEY’]¶
✅ Secret manager (Vault, AWS SM, Azure KV)¶
Best Practices¶
- Hash keys in the DB (SHA-256)
- Prefix to distinguish (sk_live_, sk_test_)
- Expiration and rotation
- Scope — minimal permissions per key
- Pre-commit hooks (gitleaks, truffleHog)
Key Takeaway¶
Hash API keys, rotate them, limit scope. Never commit them to Git.