API key security: design the lifecycle, not just the format
Secure API key management with SHA-256 hashing, one-time reveal, safe rotation, audit trails, and the principle of least privilege.
An AI API key can spend money, access customer data, and trigger workflows. Yet most platforms treat keys like passwords — generate, hash, store, done. Production needs a key lifecycle spanning generation, storage, display, usage, rotation, and revocation.
Key format and hashing
import { createHash, randomBytes, timingSafeEqual } from "crypto";
function generateKey(env: "live" | "test") {
const prefix = env === "live" ? "pk_live_" : "pk_test_";
const raw = randomBytes(32).toString("base64url");
const full = prefix + raw;
return {
full, // Show once, never log
hash: createHash("sha256").update(full).digest("hex"), // Store
preview: prefix + raw.slice(0, 12) + "..." // Display
};
}
function verify(raw: string, storedHash: string) {
const hash = createHash("sha256").update(raw).digest("hex");
return timingSafeEqual(Buffer.from(hash), Buffer.from(storedHash));
}Rotation without downtime
Create new key, deploy alongside old (dual-running), verify new key works, then revoke old. Dashboard shows both during transition. Make rotation UX so straightforward teams do it proactively every quarter. Revocation should soft-delete with timestamp — hard deletion breaks audit trails.
Updated:
Ready to ship your AI product?
Start free, route across providers, and see honest cost + readiness from day one.
Related reading
- Product
VeloxAI: the multi-model control plane for product teams
Why product teams need one API for models, agents, RAG, billing, analytics, and readiness instead of another thin provider proxy.
- Models
How to choose the right AI model for every product workflow
A battle-tested model selection framework covering cost, latency, context window, tool calling, vision, and reasoning — with real numbers and a decision matrix.
- Knowledge Base
Building a production RAG system that doesn't lie to users
A production-grade RAG pipeline needs ingestion state, chunk metadata, vector isolation, citations, queue-based indexing, and honest failure modes.