Hash API keys before storing them
Store only a SHA-256 hash of each API key and show the key once at creation, so a database leak does not expose working keys.
An API key is a password for a program. Generate it with enough randomness that a fast hash is safe, show it once and keep only the digest.
import { randomBytes, createHash } from 'node:crypto';
export function createApiKey() {
const secret = randomBytes(32).toString('base64url');
const key = `sk_live_${secret}`;
return {
key, // show once, never store
prefix: key.slice(0, 12), // store, helps users find the key
hash: createHash('sha256').update(key).digest('hex'), // store, used to look up
};
}
const { key, prefix, hash } = createApiKey();
console.log(prefix, key.length, hash.length);sk_live_xxxx 51 64The prefix in the output is the fixed text and then the first characters of a random value, so yours differs. Looking up a key means hashing what the client sent and finding that digest, which an index makes fast. A slow hash like Argon2 is not needed because the key has 256 random bits and cannot be guessed offline. See the OWASP secrets management cheat sheet.
A readable prefix such as sk_live_ also lets secret scanners recognise a leaked key. Allow several keys per user, record the last time each was used, and make revoking one a single click.