Back to 20 Concepts
cryptography-passwordsIntermediate

Developer API Keys: Prefixing (sk_live_), SHA-256 Hashed Storage & Scopes

Developer API keys authenticate programmatic machine-to-machine requests. Stripe-style API key design uses human-readable prefixes (sk_live_), high-entropy random bytes, and SHA-256 hashed storage in databases.

Intuitive Mental Model

The Master Hotel Service Key: The key has a label on the handle (sk_live_orders) so developers know its purpose, but the lock mechanism inside the door only remembers the secret pin combination (SHA-256 hash in database).

Architecture Blueprint & CodeProduction Standard
import { randomBytes, createHash } from 'crypto';

function generateApiKey(): { rawKey: string; keyHash: string; prefix: string } {
  const secretBytes = randomBytes(24).toString('base64url');
  const rawKey = `sk_live_${secretBytes}`; // Shown once to user!
  const keyHash = createHash('sha256').update(rawKey).digest('hex'); // Stored in DB
  return { rawKey, keyHash, prefix: 'sk_live_' };
}

Key Architectural Takeaways

  • Hash Stored Keys: The database stores only SHA-256 hashes of API keys; a database breach does not expose active developer keys.
  • Show Key Once: Display the full API key in the UI only upon initial generation, prompting the developer to copy it to their secret manager.
Common Architectural Pitfall

Storing plaintext developer API keys in the database, allowing unauthorized internal employees or database dumps to compromise client systems.

Production Best Practice

Always store cryptographic SHA-256 hashes of API keys in storage backends.