VeloxAI
Back to Blog
Security· 12 min read

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.

Nguyen Son Everestt
Nguyen Son EveresttFounder & Engineering Lead, VeloxAI
#api-keys#security#auth
Secure API keys
Secure API keys

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));
}
SHA-256 with timing-safe comparison

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.