Designing API Keys: Generation, Storage, Prefixes, Scopes and Rotation

How to design API keys for your product: secure random generation, identifiable prefixes, hashing at rest, scopes, expiry, rotation, leak detection.

Published December 6, 2026

If you offer an API, you will issue keys to customers. Those keys are long-lived credentials that end up in scripts, CI systems and, inevitably, public repositories. A good API key design makes keys hard to guess, easy to identify, safe to store, scoped to what they need, and painless to rotate and revoke.

The concept

Generate keys with a cryptographically secure random source, with at least 128 bits of entropy (32+ random characters in base62). Add a recognisable prefix such as sk_live_ or dso_ so humans and secret scanners can identify them, and include an environment marker (live vs test). Show the full key to the user exactly once.

Store only a hash of the key (a fast hash like SHA-256 is fine because keys are high-entropy random strings, unlike passwords), plus a short non-secret identifier for lookup and display. Attach scopes and optional expiry to each key, log usage with the key ID, and support multiple active keys so customers can rotate without downtime. Register your prefix with secret scanning programs so leaked keys are reported to you automatically.

Anatomy of a good API key

PartExamplePurpose
Prefixdso_live_Identify product and environment; enable secret scanning
Key IDk7Q2mNon-secret lookup and display ("…k7Q2m")
Secret32+ random base62 charsUnguessable credential
Checksum (optional)CRC32 suffixDetect typos and validate format offline

Verifying a key

dbvalidClient sends keyAuthorization: Bearer dso_live_…Parse prefix + key IDLookup by ID, compare SHA-256 hashconstant timeCheck scopes, expiry, revocation→ allow
Verification without storing plaintext keys.

Rotation

  1. Customer creates a second key
  2. Deploys it to their systems
  3. Confirms traffic uses the new key (last_used_at)
  4. Revokes the old key
Zero-downtime rotation with two active keys.

Practical examples

Generate and store a key (Python)

Show the plaintext once; store only the hash.

import secrets, hashlib
key_id = secrets.token_urlsafe(4)[:5]
secret = secrets.token_urlsafe(32)
api_key = f"dso_live_{key_id}_{secret}"
record = {"key_id": key_id, "hash": hashlib.sha256(api_key.encode()).hexdigest(),
          "scopes": ["articles:read"], "expires_at": None}
# return api_key to the user ONCE

Database table

Scopes, expiry, usage tracking and revocation.

CREATE TABLE api_keys (
  key_id       text PRIMARY KEY,
  account_id   bigint NOT NULL,
  key_hash     char(64) NOT NULL,
  scopes       text[] NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now(),
  expires_at   timestamptz,
  last_used_at timestamptz,
  revoked_at   timestamptz
);

Constant-time verification

Avoid timing leaks when comparing hashes.

import hmac
row = db.get_key(key_id)
valid = row and not row.revoked_at and hmac.compare_digest(row.key_hash, hashlib.sha256(presented.encode()).hexdigest())

Common mistakes

  • Storing API keys in plaintext in the database.
  • Keys without prefixes, invisible to secret scanners.
  • One all-powerful key per account with no scopes.
  • No way to have two active keys, making rotation painful.

Key takeaways

  • Generate high-entropy keys with recognisable prefixes.
  • Store hashes, show plaintext once.
  • Scope keys, track usage, support expiry and revocation.
  • Enable rotation with multiple active keys and secret scanning partnerships.

FAQ

Why is SHA-256 OK here but not for passwords?

API keys are long random strings with huge entropy, so brute force is infeasible even with fast hashes; passwords are low-entropy and need slow hashes.

API keys or OAuth?

API keys suit server-to-server access by the account owner; OAuth suits third-party apps acting on behalf of users.

How do I detect leaked keys?

Join secret scanning partner programs (for example GitHub's) using your prefix format, and monitor usage anomalies.

More Security articles