Skip to content
jshacks.dev
Security

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.

1 min read
Summarize in AI

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.

keys.jsJavaScript
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);
Text
sk_live_xxxx 51 64

The 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.

Also inAPIs
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.