How to Generate Secure API Keys
How API Key Security Differs from Passwords
API keys share some security requirements with user passwords but differ in important ways. Similarities: both need high-entropy random values, both must be unpredictable, both must not be reused. Differences: API keys are typically not memorized by humans (managed by code or config files), so they can be longer and more random; API keys often carry broader permissions (representing entire applications accessing an API), making leaks more severe; API keys are more easily leaked through accidental code commits, log recording, and similar behaviors.
Given these characteristics, API key generation and management require specialized strategies that cannot simply replicate user password best practices.
Recommended Methods for Generating API Keys
Recommended methods for generating secure API keys in different programming environments:
# Python (recommended, standard library)
import secrets
api_key = secrets.token_urlsafe(32) # 43 URL-safe chars, 256-bit entropy
api_key = secrets.token_hex(32) # 64 hex chars, 256-bit entropy
# Node.js
const crypto = require('crypto');
const apiKey = crypto.randomBytes(32).toString('hex'); // 64 chars
const apiKey = crypto.randomBytes(32).toString('base64url'); // 43 chars
# Go
import "crypto/rand"
import "encoding/hex"
b := make([]byte, 32)
rand.Read(b)
apiKey := hex.EncodeToString(b) // 64-char hex
# Shell / OpenSSL
openssl rand -hex 32 # 64-char hex
openssl rand -base64 32 # ~44-char Base64
All of the above methods use cryptographically secure random number generators, producing keys with 256 bits of entropy โ computationally infeasible to crack in practice. Never use Math.random() (JavaScript), rand() (C/PHP), or Python's random module to generate API keys; these are insecure pseudo-random number generators.
API Key Format Design
Modern API key design best practice is to use recognizable prefixes to make keys easier to identify and manage. For example: Stripe uses sk_live_ and sk_test_ prefixes; GitHub uses ghp_ (personal access tokens) and github_pat_ prefixes; OpenAI uses sk- prefix.
Benefits of this design: allows automated detection of leaked keys via code scanning (like GitHub Secret Scanning); distinguishes production from test environment keys; identifies the key issuer (useful for security review). When designing your own API, recommend using clear prefixes like app_live_ or sk_ followed by a random string.
How to Securely Store and Transmit API Keys
API key storage is the most common source of security issues. Things never to do: hardcode API keys in source code (even private repos can be accidentally made public or leaked by employees); commit API keys to Git repositories (including .env files if they're under version control); log API keys in logs (many frameworks automatically log HTTP request headers, including Authorization).
Correct approach: pass API keys through environment variables; use dedicated secrets management services in production (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager); use .env files for local development (ensure they're excluded in .gitignore); always transmit API keys over HTTPS, never over HTTP.
Emergency Response After API Key Leakage
If you accidentally commit an API key to a public repository, time is everything. Immediately (not "in a while") execute these steps: revoke the key at the API provider to make it instantly invalid; generate and deploy a new key; purge the key from Git history (using git filter-branch or BFG Repo Cleaner); check API usage logs for any anomalous calls.
From the moment you push to the repository to the first malicious bot scanning and attempting to use the key, there are typically only seconds to minutes. Therefore, even if you immediately delete the commit, you must assume the key is compromised and revoke it immediately.
API Key Rotation and Least-Privilege
Good API key management includes periodic rotation (e.g., every 90 days) and the principle of least privilege. Use separate API keys for each application or service rather than one "master key"; assign each key only the minimum permissions needed for its task; set expiration times on keys to force periodic rotation; enable API key usage logging and anomaly alerts (like calls from unknown IPs).
In team collaboration scenarios, never share the same API key among team members. Each team member or service should have their own independent key, enabling precise permission revocation when someone leaves or a key is leaked, without affecting others.
Using Online Tools to Quickly Generate API Keys
For quickly generating one-off API keys (testing, prototyping), an online password generator is a convenient choice. Select the "alphanumeric" or "hexadecimal characters" mode and generate 32โ64 character strings. For URL-safe keys, choose a mode without special characters.
Ensure the online tool generates keys locally on the client side rather than sending requests to a server โ especially important for high-privilege credentials like API keys. In production systems, always use programmatic methods (the code examples above) to generate API keys rather than relying on web tools.
Try the free tool now
Use Free Tool โ