ShieldX Toolly
Open a tool Donate
Home Home
Blog Blog
FAQ FAQ
Open a tool Donate
All guides
Beginner 3 min Crypto & Data

Secret / API Key Generator Guide

Secure API keys and tokens using crypto.getRandomValues()

Sections
3
Level
Beginner
Read
3 min
Section 01

What makes a good API key?

A good API key has high entropy, is long enough to resist brute-force, and uses a charset that's URL-safe. A 256-bit key (32 bytes) in Base64 is 43 characters — sufficient for virtually any application.

  • Hex: 64 chars for 256 bits — simple, double the length
  • Base64: 43 chars for 256 bits — compact, may need URL-safe variant
  • Base64URL: 43 chars for 256 bits — safe in URLs and JSON
  • Custom alphabet: variable — useful for readable keys
Section 02

Generating secure keys

                          // Generate a 256-bit key in hex
function generateHexKey(bytes: number = 32): string {
  const arr = new Uint8Array(bytes);
  crypto.getRandomValues(arr);
  return [...arr].map((b) => b.toString(16).padStart(2, '0')).join('');
}

// Generate a 256-bit key in Base64URL
function generateBase64UrlKey(bytes: number = 32): string {
  const arr = new Uint8Array(bytes);
  crypto.getRandomValues(arr);
  return btoa(String.fromCharCode(...arr))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=/g, '');
}
                        

WarningNever use Math.random() or Date.now() to generate API keys. They are predictable and an attacker could enumerate valid keys. Always use crypto.getRandomValues().

Section 03

API key best practices

  • Prefix keys with a readable identifier (e.g., "sk_live_")
  • Store only a hash of the key in your database
  • Show the full key only once at generation time
  • Support key rotation and revocation
  • Rate-limit by key, not by IP

TipPrefixing keys (like "sk_live_" or "pk_test_") lets you identify the key type in logs and grep for accidental commits. GitHub and Stripe both use this pattern.

Put it into practice

Try Secret / API Key Generator right now

Every concept in this guide is implemented in ShieldX. Open the tool, watch the network tab stay empty, and verify the security yourself.

Open Secret / API Key Generator

No signup · No cookies · No cost · secure.toolly.site