API-42Required
Store API keys as hashes
Show each API key once, store only its hash, and let clients hold two keys at a time so they can rotate.
How to do it
Make keys from at least 32 random bytes with a short prefix, such as exs_live_, so secret scanners can find leaked ones. Store a SHA-256 hash and the last four characters. Look keys up by hash, never by plain text. Let each key carry scopes, an owner and an expiry. Allow revoking one key without touching the other.
Examples
JavaScript example
import { createHash, randomBytes } from 'node:crypto'
const KEY_PREFIX = 'exs_live_'
const hashKey = key => createHash('sha256').update(key).digest('hex')
function issueApiKey() {
const key = KEY_PREFIX + randomBytes(32).toString('base64url')
return { shownOnce: key, stored: { hash: hashKey(key), lastFour: key.slice(-4) } }
}
Python example
import hashlib, secrets
KEY_PREFIX = "exs_live_"
def hash_key(key: str) -> str:
return hashlib.sha256(key.encode()).hexdigest()
def issue_api_key() -> dict:
key = KEY_PREFIX + secrets.token_urlsafe(32)
return {"shown_once": key, "stored": {"hash": hash_key(key), "last_four": key[-4:]}}
How to check
Search the database for any stored key value. Only hashes appear. Issue a second key for one client and revoke the first. The revoked key gets 401 on the next call, and the second key still works.
Sources
- NIST SP 800-63B, 3.1.2.2 on storing secrets hashed
- Stripe API keys, shown once and rotated with a grace period
Related rules
- ACC-30 List connected apps and personal tokens in Accounts and identity
- MED-38 Give every share link a random token and an expiry in Files and media
- APS-14 Make tokens from a secure random source in Application security
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/api-security/api-keys">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.