Generate an API Key — Free Prefixed Key Generator

Enter a prefix styleStripe, GitHub, AWS-style, your own custom text, or none — and drag the random part length slider, and the API Key Generator builds you a realistic API key with a cryptographically random suffix. Everything runs through your browser's Web Crypto API, so the key you get back never touches a server before it's yours.

32
Click Generate to create an API key
Cryptographically SecureGenerated LocallyNever Stored

Every API call your app makes is only as trustworthy as the credential behind it. This API key generator gives you cryptographically secure, random API keys in six industry-standard formats — instantly, free, and with no account required. Whether you're wiring up a payment gateway, securing a webhook endpoint, or bootstrapping a new microservice, the key you generate here is ready for production use the moment you copy it.

What Is an Online API Key Generator?

What Is an API Key?

An API key is a unique, opaque credential that a client application presents to a backend system to prove its identity and gain access to protected resources. Unlike a username-and-password pair, an API key is a single string — typically a random key with an api key length of 16 to 256 characters — transmitted in request headers, query parameters, or the access header of every HTTP call. The backend looks up the key in its database, confirms the associated access rights and privilege levels, enforces throttling, and either grants or denies access. Because each key acts as an identifier and an access credential in one, it doubles as a lightweight verification method for backend-to-backend communication, pipeline secrets, webhook secrets, and mobile app verification without the overhead of a full delegated-access flow.

Generate Secure, Random API Keys for Your Apps — Free and No Sign-Up Required

An api key generator automates what would otherwise be an error-prone manual task: producing a sufficiently long, unpredictable, unique key every time. Rolling your own key with Math.random(), window.performance.now(), new Date().getTime(), or performance.now() is dangerous because these sources are predictable and fail basic statistical quality tests. A proper generator relies on a CSPRNG — a cryptographically secure pseudorandom number generator — seeded by the operating system's entropy pool, which draws from hardware random byte generation events to guarantee unpredictability and make guessing attacks computationally infeasible.

This tool runs entirely via client-side generation in your browser using the browser's built-in cryptography interface. That means your generated keys are never logged, never transmitted to a backend, and never leave your device. The output is available as plain text, CSV, or JSON for seamless connection into configuration files and config stores.

Privacy guarantee: Generated values are computed locally. No keys are stored remotely, no account is needed, and no request is sent — ever. This is a fully client-side, no sign-up required tool.

How to Use This Secure API Key Generator

Step 1 — Select Key Length and Understand Key Length Security

Use the key length slider to choose a value between 8 to 256 characters. Length is the single biggest lever you have over entropy — every additional character multiplies the number of possible keys by the size of the alphabet used, making brute-force resistance grow exponentially. Here are the practical benchmarks:

  • 16 chars — Minimum for development testing; roughly 48–96 bits of unpredictability depending on format. Acceptable for non-sensitive internal access strings.
  • 32 chars — The industry-standard recommendation for live keys. A 32-character alphanumeric key yields ~190 bits of entropy — far beyond anything a modern attacker could crack.
  • 40 chars — High-security tier, preferred for financial interfaces and payment processing keys where regulatory standards demand elevated strength.
  • 64 chars — Maximum protection for the most sensitive systems. Suitable for signing keys and long-lived private values.
  • 128+ chars — Paranoid-level protection or strict adherence to FIPS standards and NIST SP 800-90A mandates. Also useful for HMAC signing keys.

Step 2 — Choose the API Key Format

The key format controls which alphabet is used and how the raw random bytes are encoded into a printable string. Select the format that matches your platform's output requirements and URL handling constraints:

  • Alphanumeric (A-Za-z0-9) — A 62-character pool that is compatible with virtually every system and uses only alphanumeric characters. The most versatile choice for general service access verification.
  • Hexadecimal (0-9a-f) — A 16-symbol set producing compact binary representation. Common for HMAC signing keys and digest-based access strings where hex encoding is expected.
  • Base64 (RFC 4648) — A 64-symbol set including +, /, and = padding. Most compact encoding; yields 6 bits per character. Use when space efficiency matters and the transport layer handles non-web-safe characters.
  • Base64 URL-Safe — Replaces + and / with - and _, removes padding. This encoding is used by signed access strings and delegated-access bearer tokens. Safe to embed in URLs and HTTP headers.
  • UUID v4 (RFC 4122) — Generates a 128-bit format identifier in the canonical xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx pattern with 122 bits of unpredictability. A compliant UUID following the RFC 4122 version 4 specification. Use this when your system expects a standard uuid string as a unique id.
  • Numeric Only (0-9) — Digits-only output for verification codes and numeric-only legacy systems. Lower unpredictability per character, so use longer lengths.

Step 3 — Add a Custom Prefix (Optional)

The custom prefix input lets you prepend a human-readable label to every generated key. Prefixes are an industry pattern pioneered by payment platforms: they make it immediately obvious what type of key you're looking at and which environment it belongs to. The api_ prefix convention is widely used for general-purpose access keys. Common conventions include:

  • sk_ — Private key prefix for sensitive, backend-only credentials (the sk_ prefix follows the Stripe pattern for live private keys)
  • pk_ — Shareable key prefix for client-facing publishable keys
  • api_ — General-purpose service access prefix
  • test_ — Test environment keys to prevent accidental use in live systems
  • prod_ — Live environment keys

You can also set a separator character between the prefix and the random portion. Setting a separator clearly delineates the key prefix from the random component, which aids both readability and programmatic parsing.

Step 4 — Generate and Copy Your API Keys

Once you've configured your options, click the generate button to instantly produce your key. You can set the key quantity to bulk-generate up to 25 keys at once — useful for provisioning multiple environments, seeding a staging database, or pre-generating keys for a new user cohort. Hit the one-click copy button to copy keys directly to your clipboard, or use the export buttons to download an exported key file as text, CSV, or JSON. When you export CSV or export JSON, the file contains sensitive values — delete the file after importing it into your system. If you want to export TXT, that's also available for simple line-delimited use.

Key Format, Key Length, and Prefix Reference for Free API Key Generation

API Key Format Comparison Table

FormatCharacter SetEntropy per CharExample OutputBest Use Case
Alphanumeric (A-Za-z0-9)62-character pool~5.95 bitssk_vR8n2KmPqL4xWj9TcFaG3dHGeneral access verification, standard keys
Hexadecimal (0-9a-f)16 symbols4.0 bitsapi_4a7f3c9e2b8d1f6a5c3e9d2aHMAC keys, digest-based access strings
Base64 (RFC 4648)64 symbols (incl. +/=)6.0 bitspk_8vR2xK/mL+3wN9Qa==Compact storage, binary-safe transport
Base64 URL-Safe64 symbols (- and _ instead of +/)6.0 bitstoken_8vR2xK-mL_3wN9QaSigned access strings, delegated-auth keys, URL embedding
UUID v4 (RFC 4122)Hex + hyphens, 128-bit format122 bits totalf47ac10b-58cc-4372-a567-0e02b2c3d479Standard compliance, unique id fields
Numeric Only (0-9)10 digits3.32 bits748293650182Verification codes, numeric-only legacy interfaces

Common API Key Prefixes: sk_, pk_, api_, test_

Prefix conventions encode metadata directly into the key string, making accidental misuse far less likely. The sk_live prefix signals a live private key — if this string appears in a log or a public repository, automated scanners (including GitHub's secret scanning) will flag it immediately. The sk_test prefix and pk_live prefix follow the same logic. Here is how major platforms structure their keys:

PlatformKey TypePrefixExampleNotes
StripeLive Secretsk_live_sk_live_51H7xyzABC...Backend use only, do not expose
StripeTest Secretsk_test_sk_test_4eC39HqLyjWD...Development/staging environment
StripePublishablepk_live_pk_live_abc123...Shareable frontend key, safe in client code
SendGridAPI KeySG.SG.ngeVfQFxBn-X...Access credential for email delivery
AWSAccess Key IDAKIAAKIAIOSFODNN7EXAMPLEPaired with a private value for cloud services
GitHubPersonal Tokenghp_ghp_16C7e42FxyzABC...Repository access credential
Custom RESTAPI Keyapi_api_1234abcdef5678General-purpose service access key

API Keys vs. OAuth vs. JWT — Choosing the Right Authentication Method with This Free Online API Key Generator

API Keys — When Simplicity Wins

API keys are ideal for backend-to-backend communication, service verification, and any scenario where the calling system is trusted and fully controlled by you. They offer low configuration overhead, are stateless on the client side, and work easily with throttling and usage quotas. Attach the key in the Authorization header as an access credential or in a custom X-API-Key header, and your backend validates it on every request. Best for: REST endpoint verification, webhook signing, pipeline secrets, microservice access control, and service-to-service auth.

OAuth 2.0 — When Users Are Involved

OAuth is the right verification approach when a user needs to grant third-party access to their data without sharing their password. The client identifier and client private value are exchanged for short-lived access credentials with adjustable privilege levels and built-in expiry. OAuth 2.0 carries a higher configuration overhead but delivers superior protection for user-delegated access flows. Use it for single-page applications, mobile app connections, and any scenario involving user-delegated access rights.

JWT Tokens — For Stateless Distributed Systems

JWT tokens (JSON Web Tokens) embed claim-based access rights directly into the payload, enabling stateless verification across distributed systems and microservices. Because the backend validates the signature rather than looking up the credential in a database, signed JSON tokens are excellent for microservice access control and cloud-native architectures. The tradeoff: revocation is harder without a blocklist. This format uses base64 encoding for its header and payload components, making it web-safe by design.

REST vs. GraphQL Authentication Considerations

For REST endpoints, access keys map naturally to resource-level control: one key per privilege tier. For query-based interfaces, you often need fine-grained access rights at the query level — controlling who can execute which queries (users:read, users:write, admin:settings, payments:process, analytics:export, webhooks:create). Both REST and query-based interfaces support key-based access via request headers, but the flexibility of query languages makes delegated-access flows with custom privilege layers or dedicated access-control handlers a more scalable choice for complex scenarios.

FeatureAPI KeysOAuth 2.0JWT Tokens
Setup Complexity🟢 Simple🟡 Moderate🟡 Moderate
Security Level🟡 Medium🟢 High🟢 High
Token Expiry🔴 Manual rotation🟢 Automatic🟢 Built-in
Permissions ModelFixed privilege levelsAdjustable privilege levelsClaim-based access rights
StatefulnessBackend lookupBackend + access credentialsStateless verification
Best ForBackend-to-backend, webhooks, CI/CDUser delegation, third-party accessMicroservices, distributed systems

Platform-Specific API Key Formats and Real-World Examples

Stripe — The sk_live_ and pk_ Pattern

Stripe's key structure is the most widely imitated format in software development. Each Stripe account gets four keys covering the combination of environment (live vs. test) and type (private vs. publishable). The sk_live_ key is your live private key — used exclusively for backend operations like creating charges and managing subscriptions. The pk_live_ publishable key is your shareable identifier that safely appears in frontend code to tokenize payment details. The sk_test prefix marks development keys; the pk_ prefix for test is pk_test_. This environment separation pattern (dev/staging/prod) is now considered an industry standard for any service that handles live keys separately from development keys.

A realistic Stripe-style key-pair exchange in a fetch() call looks like this:

JavaScript — Stripe-style key-secret pair fetch()
// Public key identifies the client (safe in frontend)
const PUBLIC_KEY = 'pk_live_51H7xyzABCdefGHIjklMNOpqR';

// Private key proves ownership (backend only — do not expose in browser code)
// Stored in process.env.STRIPE_SECRET_KEY
const response = await fetch('https://api.stripe.com/v1/charges', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.STRIPE_SECRET_KEY}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: 'amount=2000¤cy=usd&source=tok_visa'
});

SendGrid — Bearer Token Format

SendGrid uses a bearer token format prefixed with SG.. Like all well-designed platform keys, the SendGrid key is transmitted via the Authorization header: Authorization: Bearer SG.ngeVfQFxBn-X9hnPq.... This is a web security credential suited for email delivery automation. Because SendGrid keys carry full account access by default, you should apply the least-privilege principle and generate scoped keys that cover only the access rights your connection actually needs (e.g., mail.send only, rather than full account admin).

Key-Secret Pairs — Dual Authentication

Key-secret pairs are a dual-credential pattern where two related values serve different roles. The shareable identifier travels in every request and acts as a reference — it can be logged safely in access logs. The private value never appears in logs, is stored in encrypted storage, and is used for HMAC signing of request payloads to fulfill the web security requirement for payload integrity. The backend recomputes the HMAC signature using the private value and compares it against the value in the submission for payload verification. This pattern underpins AWS access key verification (AKIA… identifier + private value), delegated-access client ID + client private value flows, and webhook signing for endpoint verification. Use key-secret pairs any time you need to prove both identity (who is calling) and ownership (that the caller holds the private value) without transmitting the private value itself.

Code Examples: Programmatic API Key Generation

Node.js and JavaScript — crypto.randomBytes()

The Node.js crypto module's crypto.randomBytes function is the correct tool for programmatic key generation in JavaScript environments. It calls the operating system CSPRNG directly — on Unix-based systems this is /dev/urandom; on Windows it is BCryptGenRandom. Never use Math.random() or Math.floor() for security-sensitive strings; these are standard pseudorandom generators with no cryptographic guarantee. The generateUUID pattern that uses timestamp-based seeding is similarly unsafe for production use in any devops pipeline or live environment.

Node.js — Generate a production API key with sk_live_ prefix
const crypto = require('crypto');

// Generate a cryptographically secure 32-character base64url key
// with a sk_live_ prefix following the Stripe pattern
function generateApiKey(prefix = 'sk_live_', byteLength = 24) {
  const randomPart = crypto.randomBytes(byteLength).toString('base64url');
  return `${prefix}${randomPart}`;
}

const apiKey = generateApiKey();
console.log(apiKey);
// Output: sk_live_8vR2xKmL3wN9QaBcDeFgHiJk

// For key pairs:
const publicKey  = generateApiKey('pk_live_', 16); // shareable frontend identifier
const secretKey  = generateApiKey('sk_live_', 32); // private value — never expose
console.log({ publicKey, secretKey });

Generate an API Key in the Terminal (Linux and macOS)

For local key generation without opening a browser, use your terminal directly. The openssl rand command draws from the operating system's entropy pool and is available on every Unix-based system. The one-liner below is equally portable and produces a base64 encoded key with a prefix in a single command. These terminal approaches are useful in a devops workflow where scripting and automation are preferred:

Terminal — Node.js one-liner (base64url, sk_live_ prefix)
node -e "console.log('sk_live_' + require('crypto').randomBytes(24).toString('base64url'))"
Terminal — OpenSSL rand (alphanumeric, 32 chars)
echo "api_$(openssl rand -base64 32 | tr -dc 'a-zA-Z0-9' | head -c 32)"
Python — secrets module (token_urlsafe)
python3 -c "import secrets; print(f'sk_live_{secrets.token_urlsafe(24)}')"

The Python secrets module (token_urlsafe) is the recommended tool in Python 3.6+. It uses secure random byte generation internally via os.urandom. In Java and Kotlin, use SecureRandom for cryptographically strong values. In Go, use crypto/rand. In Ruby, use SecureRandom. In C#, use RandomNumberGenerator for ASP.NET Core Web interfaces. In C++, use random_device for game engines and native applications. In PHP, use random_bytes() with base64 encoding. Every language has a CSPRNG — the key is always to use the cryptographic module, never the standard math library.

Access Control Handler — Validating API Keys

Generating a key is only half the story. Here is a minimal but production-ready access control handler implementation that validates incoming keys, checks privilege levels, and enforces access controls — demonstrating how key-based verification plugs into a real backend. This pattern is fundamental to web security in any service-oriented architecture, and an important part of any security audit checklist for production deployments:

Express.js — API key validation middleware with permission scopes
const crypto = require('crypto');

// In production: load from a database or secrets vault, not a hardcoded Map
const API_KEYS = new Map([
  ['sk_live_8vR2xKmL3wN9QaBcDeFgHiJk', {
    permissions: ['users:read', 'payments:process'],
    rate_limit: '1000/hour',
    api_version: 'v2',
    scopes: ['read', 'write']
  }]
]);

function requirePermission(requiredPermission) {
  return (req, res, next) => {
    // Extract access credential from Authorization header
    const authHeader = req.headers['authorization'] || '';
    const apiKey = authHeader.startsWith('Bearer ')
      ? authHeader.slice(7)
      : req.headers['x-api-key'];

    if (!apiKey) {
      return res.status(401).json({ error: 'API key required' });
    }

    const keyData = API_KEYS.get(apiKey);
    if (!keyData) {
      return res.status(401).json({ error: 'Invalid API key' });
    }

    const hasPermission =
      keyData.permissions.includes('*:*') ||
      keyData.permissions.includes(requiredPermission);

    if (!hasPermission) {
      return res.status(403).json({
        error: 'Insufficient permissions',
        required: requiredPermission,
        granted: keyData.permissions
      });
    }

    req.apiKeyData = keyData;
    next();
  };
}

// Route usage
app.get('/users',  requirePermission('users:read'),      (req, res) => res.json({ users: [] }));
app.post('/users', requirePermission('users:write'),     (req, res) => res.json({ created: true }));
app.post('/pay',   requirePermission('payments:process'),(req, res) => res.json({ charged: true }));

Cryptographic Security Standards Behind This Generator

The entropy calculation for any generated key follows a straightforward formula rooted in cryptography. For an alphanumeric key drawn from a 62-character pool using secure random selection:

$$\text{entropy} = \text{key\_length} \times \log_{2}(\text{alphabet\_size})$$

For a 32-character alphanumeric key:

$$\text{entropy} = 32 \times \log_{2}(62) \approx 32 \times 5.954 \approx 190.5 \text{ bits of entropy}$$

For a hexadecimal key of the same length:

$$\text{entropy} = 32 \times \log_{2}(16) = 32 \times 4 = 128 \text{ bits}$$

At 190 bits, a 32-character alphanumeric key is computationally infeasible to crack by brute force: even at a trillion guesses per second, you would need more attempts than there are atoms in the observable universe. This generator meets NIST SP 800-90A and FIPS standards regulatory requirements through its use of the browser's built-in cryptographic interface and a validated entropy source. The underlying generator is seeded by hardware-level OS events, not software state, and passes NIST randomness test validation for statistical quality.

API Key Security Best Practices for Developers

Security Tips: Storage, Environment Variables, and Secrets Management

The biggest threat to key protection is not cryptographic weakness — it's accidental exposure. A key with 190 bits of entropy is meaningless if it ends up in a public repository or in code history. Follow these rules without exception to store securely and maintain proper key hygiene, which should be part of any regular security audit:

  • Never hard-code keys in source code, configuration files committed to code history, or browser-side JavaScript. Even a private repository can become public, and git history is permanent.
  • Use environment variables: store keys in .env or .env.local files, load them via process.env.API_KEY in Node.js/Express/Fastify, or REACT_APP_API_KEY for frontend frameworks. Add .env to .gitignore immediately.
  • Keep private keys out of frontend bundles, browser console logs, or error responses. Keys meant for backend operations must stay on the backend.
  • Use a secrets vault (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager) for live infrastructure. These provide encrypted storage, access logging, and automatic rotation — essential for devops teams managing many services.
  • Never log private key values in application logs. Log the key prefix or a digest of the key for traceability — never the full private value.
  • Transmit over HTTPS only: never send keys over plain HTTP. Use TLS for all headers carrying access credentials, which is a fundamental web security requirement.
  • Monitor key usage: log every verified request with a timestamp and client identifier. Anomalous patterns (spikes, off-hours requests, unusual endpoints) may indicate exposure or reuse risk.
Generated it? Store it safely. Once you close this tab, your key is gone — it never leaves your device after generation. Copy your key and paste it immediately into your .env file or secrets vault. If you lose it, generate a new one — it takes two seconds.

Permission Presets and the Least-Privilege Principle

Every key should carry only the access rights it actually needs — this is called key scoping or the least-privilege principle. Define permission presets in your key management layer: a key used by a read-only analytics dashboard should carry only analytics:read and analytics:export privilege levels, not admin:settings or payments:process. Granular access controls and custom privilege levels limit the blast radius if a key is compromised. Apply throttling at the key level too — a per-key request cap of 1,000 requests per hour is appropriate for most connections and serves as a natural circuit breaker against abuse. Implement a throttle preset in your access handler so every key gets a sensible default even if not explicitly configured.

How to Rotate and Revoke API Keys

Key rotation is a mandatory practice for application protection. Rotate keys at least every 90 days for live credentials — this is the standard recommended by most security frameworks and is a common item on any security audit checklist. After a team member leaves, rotate all keys they had access to immediately. For automated deployment environments and pipeline secrets, consider a shorter rotation window. The process for key rotation is: generate a new key, update it in all services and config stores, verify the new key works end-to-end, then revoke the old key. Log key usage throughout the transition to confirm the old key is no longer active before deletion. Plan for key expiry as part of your secrets management strategy — keys should not be indefinitely valid by default.

Entropy, Randomness, and the Math Behind a Cryptographically Secure API Key

Why CSPRNG Beats Math.random() for API Key Generation

A secure random number generator differs from a standard pseudorandom number generator in one critical way: its output is computationally indistinguishable from true randomness, even to an adversary who knows the algorithm. Math.random(), timestamp-based seeds, and performance.now() — as seen in some CodePen generateUUID implementations — all derive their state from predictable inputs. A UUID generated with Math.floor(d + Math.random() * 16) and a timestamp seed fails NIST statistical tests and is vulnerable to timing attacks. By contrast, the browser's cryptography interface and Node.js's crypto.randomBytes tap directly into the operating system CSPRNG, which combines hardware randomness, interrupt timing, and system-level unpredictability into a pool that passes NIST SP 800-90A standards.

The practical consequence: at 40 characters of alphanumeric output, you have ~238 bits of unpredictability. The number of possible keys is \(62^{40} \approx 8.39 \times 10^{71}\) — far beyond guessing reach. Even exhaustive attacks at a trillion attempts per second would need vastly longer than the age of the universe. That is maximum entropy by any industry definition.

Client-Side Generation and the Privacy Guarantee

This tool operates entirely through client-side generation — your browser computes every key locally using the principles of cryptography. There are no external calls, no backend logs, and no remote key storage on any system. The keys never leave your device and remain completely private. This design is intentional: it eliminates the risk of a supply-chain attack or a backend breach exposing your freshly generated access values. The exposure risk is zero because there is no backend. This is also why the tool is genuinely free — there is no backend infrastructure to run.

Related Security and Developer Tools

Related Tools for Developers

If you found this api key generator useful, these companion tools cover adjacent protection and identity use cases:

  • Password Generator — Generate strong, random passwords with configurable length and character types. Ideal for account access values and secrets management.
  • UUID Generator — Generate RFC 4122-compliant version 4 UUIDs for database primary keys, unique id fields, and distributed system identifiers. Produces the standard RFC 4122 version 4 format.
  • Hash Generator — Compute MD5, SHA-1, SHA-256, and SHA-512 digests for input strings. Useful for payload verification, HMAC signature validation, and integrity checking.
  • Random String Generator — A flexible tool for producing access strings, verification codes, session IDs, and test data in any alphabet and length.
  • JWT Decoder — Decode and inspect signed JSON tokens without verification to debug claims, check expiry, and inspect embedded access rights and claim payloads.

Frequently Asked Questions

Does the prefix add any real security?
No -- the prefix is purely cosmetic and organizational (it lets you and automated scanners like GitHub's secret scanning instantly identify what kind of key a string is at a glance). All of the actual unguessability comes from the random suffix; a recognizable prefix doesn't weaken a key's security, since the prefix itself is never secret.
Why do real services like Stripe use prefixes like sk_live_?
It lets both humans and automated tooling identify a leaked credential's type and severity instantly -- sk_live_ signals a live secret key needing immediate rotation, while pk_live_ signals a publishable key that's safe to expose client-side by design. Following the same convention in your own API makes leaked-key triage much faster.
How long should the random part be?
32 characters (the default) from a 62-character alphanumeric set gives roughly 190 bits of entropy, far more than needed to resist brute-forcing. Go shorter (16-20) only if your system has a strict length constraint; there's little benefit to going much longer.
Can I use this as a real production API key?
The key itself is generated with genuine cryptographic randomness and is suitable for production use, but you're responsible for hashing it before storing it server-side (never store API keys in plaintext, the same way you'd never store a password in plaintext) and for building proper revocation and rotation support around it.
Is the generated key sent anywhere?
No. It's generated entirely in your browser using the Web Crypto API's cryptographically secure random number generator -- nothing is transmitted, logged, or stored.