Stockio

How to Store API Keys Securely: Secure Token Generation

Generate unpredictable API tokens, store verifiers safely, and build expiration, rotation, and revocation workflows without confusing password hashes with keys.

By Chidi Nwosu

Backend Engineer ·

On this page

A token can look random and still be predictable. A password can be hashed and still be inexpensive to crack. Security depends on how a secret is generated, what an attacker can observe, and how the server verifies and retires it—not on whether the output resembles a long hexadecimal string.

This guide separates password storage from API token management, demonstrates cryptographically secure token generation, and outlines a practical credential lifecycle. The examples focus on opaque bearer tokens; provider-issued keys and delegated authorization require additional rules specific to those systems.

Separate secrets, encodings, and verifiers

A password is usually chosen by a person and may have low entropy. An API token should be generated by a cryptographically secure random number generator. A hash is a one-way transformation, while Base64 is only an encoding. None of these terms is interchangeable.

Use the Password & API Key Secure Hash Generator below with synthetic examples to inspect output formats and understand that distinction. Do not paste production passwords, live API keys, or customer secrets into a general-purpose utility. A demonstration tool is not your application's credential service.

Choose the verification model before choosing a function. If your server only needs to verify a presented token, it can store a verifier rather than the raw secret. If it must later send a provider key to another service, a one-way hash cannot recover that key; controlled secret storage is required instead.

Generate opaque tokens from cryptographic randomness

Use the runtime's cryptographic random source, never timestamps, counters, usernames, or Math.random(). For an opaque API token, 32 uniformly random bytes provide 256 bits of entropy. Encoding those bytes changes their representation, not their unpredictability.

The following server-side Node.js example generates a token and its SHA-256 verifier. The prefix identifies the credential family; it contributes no secret entropy. This is an issuance building block, not a complete authentication endpoint.

import { createHash, randomBytes, timingSafeEqual } from "node:crypto";

function digestToken(token: string): Buffer {
return createHash("sha256").update(token, "utf8").digest();
}

export function issueToken() {
const secret = randomBytes(32).toString("base64url");
const token = "sk_live_" + secret;
return {
  token,
  verifierHex: digestToken(token).toString("hex"),
};
}

export function matchesVerifier(token: string, storedHex: string): boolean {
if (!/^sk_live_[A-Za-z0-9_-]{43}$/.test(token)) return false;
if (!/^[a-f0-9]{64}$/.test(storedHex)) return false;
const candidate = digestToken(token);
const expected = Buffer.from(storedHex, "hex");
return timingSafeEqual(candidate, expected);
}

For browser-side cryptographic randomness, MDN documents getRandomValues. Browser generation can be appropriate for specific protocols, but your application should generally issue server-managed API credentials on the server, where authorization and audit controls live.

Give each token a separate public record ID for lookup and management. A database can also locate a record by the computed verifier digest. Do not scan every credential and compare it in a loop. Neither lookup strategy replaces rate limiting or careful error handling.

Store password hashes differently from token verifiers

High-entropy tokens and human passwords have different attack economics. A fast digest can be appropriate for a uniformly random 256-bit token because exhaustive guessing remains infeasible. The same fast digest is inappropriate for ordinary passwords, which attackers can guess from dictionaries and leaked collections.

For passwords, use a maintained implementation of Argon2id with a unique salt and parameters aligned with current deployment guidance. The OWASP Password Storage Cheat Sheet provides concrete algorithm and work-factor recommendations. Benchmark verification under realistic concurrent load before deployment.

Let the password library generate salts and serialize algorithm parameters. Do not invent a custom sequence of SHA-256 rounds. Store the resulting password hash string, and support parameter upgrades during successful authentication when your library supports rehash detection.

For random API tokens, store the verifier with a record containing owner, scopes, creation time, expiration time, last-used time, and revocation status. A verifier protects against immediate reuse after a database-only leak, but it does not make a compromised application server harmless. An attacker controlling issuance or verification can bypass those protections.

Use the hash exploration tool only to compare synthetic outputs while documenting the chosen design. A tool's ability to produce a digest does not establish that the algorithm is suitable for password storage.

Keep credentials outside public application surfaces

A bundled frontend variable is public configuration, even if its name contains SECRET. Users can inspect downloaded JavaScript and network requests. Keep privileged provider credentials on the server, and have the browser call a server endpoint that checks authorization before making the upstream request.

Avoid credentials in URLs, where they can enter browser history, referrer data, analytics, and proxy logs. For API requests, use an authorization header over HTTPS. Then configure log redaction explicitly: headers can still leak through debugging middleware or observability tooling.

The OWASP Secrets Management Cheat Sheet describes centralized storage and lifecycle controls. A managed secret store or platform integration is preferable to scattering production values across local files and deployment scripts.

Scope credentials to the smallest useful capability. A reporting integration should not receive billing-write permission. Separate development and production keys so a test environment cannot silently modify production data.

For browser sessions, evaluate secure, HttpOnly cookies and appropriate CSRF protections rather than automatically keeping long-lived bearer tokens in local storage. HttpOnly reduces script access to the cookie; it does not eliminate every consequence of an XSS vulnerability. The XSS prevention guide explains the complementary frontend defenses.

Build rotation and revocation into the first release

A credential needs an operational lifecycle, not just an issuance button. Show a newly generated token once, communicate that it cannot be recovered, and provide an authenticated replacement flow. Require appropriate reauthentication for sensitive credential-management actions.

  1. Authenticate the user and authorize the requested scopes before issuance.
  2. Generate the token, persist its verifier and metadata, then reveal the secret once.
  3. Check expiration, revocation, account status, and scopes on every protected request.
  4. Apply request limits and record safe audit events without storing token contents.
  5. Allow replacement credentials to overlap briefly when uninterrupted rotation is necessary.
  6. Revoke the old credential after the client confirms migration, or sooner during an incident.

Make revocation latency explicit. If authorization results are cached for five minutes, a database update alone may not immediately disable the token. Invalidate relevant caches or document the maximum delay and choose it according to risk.

Test missing headers, malformed tokens, expired records, revoked credentials, and insufficient scopes. Return useful status codes without revealing whether a guessed account or credential record exists. Add alerts for unusual usage without logging the secret that triggered them.

Keep a short incident checklist with an owner, revocation steps, affected-service inventory, and verification of replacement deployment. The frontend engineering collection provides related implementation topics, but credential policy should receive dedicated security review before production launch.

Key takeaways

  • Generate unpredictable tokens with cryptographic randomness rather than timestamps or convenience random functions.
  • Use password-specific hashing for human passwords and suitable verifiers for high-entropy API tokens.
  • Keep production secrets out of browser bundles, URLs, analytics, and diagnostic logs.
  • Store ownership, scopes, expiration, and revocation metadata alongside each verifier.
  • Design rotation, cache invalidation, and incident response before issuing the first live credential.
  • Treat examples and interactive utilities as learning aids, not substitutes for a reviewed authentication system.
Featured sponsor

Reach designers & developers at work

Put your product next to the tools people use every day. One sponsor per placement, no tracking pixels.

Become a sponsor

Keep reading

Related articles

More in Backend & APIs
Backend & APIs

Argon2 vs bcrypt: Secure Password Hashing and Migration

Implement password storage with Argon2id, maintain bcrypt safely, benchmark resource costs, and upgrade existing hashes during login without exposing plaintext secrets.

Includes: Password & hashChidi NwosuChidi Nwosu
VPN & Online Privacy

10 Best Private Browsers and Search Engines

Compare privacy-minded browsers and search engines for daily use, including tracking protections, familiar features, and the compromises to consider before switching.

Includes: Password & hashRavi DesaiRavi Desai
VPN & Online Privacy

8 Best Encrypted Email and Messaging Apps

Compare eight email and messaging services with encryption features, practical trade-offs, and clear advice on choosing the right option for private conversations and everyday correspondence.

Includes: Password & hashRavi DesaiRavi Desai
Smartphones & Tablets

8 Best Phone Settings to Change Right Away

Make your phone safer, quieter, and easier to use with eight practical settings covering screen locks, backups, permissions, notifications, and battery habits.

Includes: Password & hashDaniel KimDaniel Kim
Online Security & Scams

7 Best Antivirus Apps for Windows and Mac

Choose antivirus protection that fits your computer, budget, and comfort level, with practical comparisons of seven established options for Windows and Mac.

Includes: Password & hashRavi DesaiRavi Desai
Online Security & Scams

6 Best Authenticator Apps for Two-Factor Login

Compare six authenticator apps for stronger account logins, with clear advice on backups, phone changes, recovery codes, and choosing a setup you can maintain.

Includes: Password & hashRavi DesaiRavi Desai