▶ Random Everything - 100+ Free Generators // v2.8.5
root@generate-random:~/api-keys/code-examples$ _

API Key Generation Code Examples

256-bit API keys in PHP, JavaScript, Python, Java, C#, C++, Ruby and Go

Every example reads 32 bytes from a secure random source and encodes them two ways: 64 hexadecimal characters such as a7f3e9c2…b3f6a9, or 43 URL-safe Base64 characters such as p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo. Some add a prefix like sk_live_. The guide covers key length, format, storage and checking; each language section then shows the code and its language-specific details. Prefer no code? The interactive API key generator does the same in the browser.

How long an API key should be

An API key is a bearer secret: whoever holds it is the client. Its only defense is that nobody can guess it, so its strength is the number of random bits behind it, not the length of the string. 128 bits (16 bytes) is the floor; 256 bits (32 bytes), as in every example here, leaves a wide margin and costs nothing. Encoding changes the length but not the strength:

  • Hex: 2 characters per byte, so 32 bytes become 64 characters.
  • URL-safe Base64 without padding (RFC 4648 §5): 4 characters per 3 bytes, so 32 bytes become 43 characters using A–Z a–z 0–9 - _.
  • Base32 or Base58 avoid ambiguous characters for keys people read aloud, at roughly 5.0 or 5.9 bits per character.

Only a CSPRNG may produce the bytes

Security matters fully here. Keys must come from the operating system generator: random_bytes(), crypto.randomBytes() or crypto.getRandomValues(), secrets.token_*, SecureRandom, RandomNumberGenerator, crypto/rand, or OpenSSL RAND_bytes() in C++. Never Math.random(), rand(), mt_rand() or java.util.Random, whose state can be recovered from a few outputs. Also avoid deriving keys from timestamps, user IDs or hashes of them. A UUID is not a substitute either: a v4 UUID carries only 122 random bits, and RFC 9562 warns that UUIDs should not be assumed hard to guess.

Prefixes, storage and verification

A short prefix such as sk_live_ or sk_test_ tells humans and secret scanners what the key is and which environment it belongs to, which helps when one leaks into a repository or a log. It adds no strength, so put it in front of the full 32 random bytes, not in place of some.

Show the key to the user once and store only a hash. Because the key is already 256 random bits, a single SHA-256 is enough; slow password hashes such as bcrypt or Argon2 exist to protect low-entropy human passwords and only add latency to every API call. Index the hash, look the request up by it, and keep a separate non-secret key ID or the first few characters for display in dashboards. Comparing against a stored plaintext key should use a constant-time function.

Common mistakes

  • Passing keys in the query string. URLs end up in server logs, proxies and browser history. Send keys in a header (Authorization: Bearer … or X-API-Key).
  • Using standard Base64 in URLs and headers. +, / and = need escaping; use the URL-safe alphabet without padding.
  • Confusing byte count with character count. token_hex(16) and SecureRandom.hex(16) give 16 bytes, 32 characters, 128 bits. Asking for a "32-character key" from a hex function gives half the strength a reader expects.
  • Keys that never expire. Support several active keys per client so a key can be rotated without downtime, record when each was last used, and revoke unused ones.
  • Logging the key. Request loggers and error trackers capture headers by default; redact the key header everywhere.

Common Use Cases

  • Authentication keys for public REST and GraphQL APIs
  • Service-to-service credentials between internal microservices
  • Webhook signing secrets for HMAC request signatures
  • Client secrets for OAuth 2.0 confidential clients
  • Per-environment live and test keys with identifying prefixes

API Key Generation Code Examples in PHP

Generate cryptographically secure API keys in PHP using random_bytes() for authentication systems. API keys should be random, unpredictable, and contain sufficient entropy (128-256 bits recommended).

<?php
// Generate 32-byte (256-bit) API key
function generateApiKey(int $length = 32): string {
    $bytes = random_bytes($length);
    return bin2hex($bytes);
}

// Example: 64-character hexadecimal API key
$apiKey = generateApiKey(32);
echo $apiKey;
// Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

// Base64 URL-safe encoding (shorter, 43 chars for 256 bits)
function generateApiKeyBase64(int $length = 32): string {
    $bytes = random_bytes($length);
    return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}

$apiKeyBase64 = generateApiKeyBase64(32);
echo $apiKeyBase64;
// Output: "p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"

// Calculate entropy: 32 bytes = 256 bits
// Collision probability: 1 in 2^256 (astronomically low)

How it works in PHP

This implementation uses PHP's random_bytes() function which provides cryptographically secure random data. The hexadecimal encoding produces a 64-character string for 32 bytes, while Base64 URL-safe encoding produces a shorter 43-character string with the same entropy. Both formats are suitable for API keys, with Base64 being more compact for transmission and storage.

Sample output

Hexadecimal (64 chars): a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
Base64 URL-safe (43 chars): p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo
Base64 URL-safe (32 bytes): kL7mP9tR3wX6hY2jN8vB4qS1eC5fA9xD0pT7gU6iM3n

PHP notes

  • random_bytes() (PHP 7+) throws if no secure source is available rather than returning weak bytes.
  • Store hash('sha256', $apiKey) and compare with hash_equals(), which runs in constant time.
  • sodium_bin2base64($bytes, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING) replaces the strtr/rtrim chain.

API Key Generation Code Examples in JavaScript

Generate cryptographically secure API keys in JavaScript using the Web Crypto API for browsers or Node.js crypto module. Suitable for authentication tokens and service-to-service communication.

// Node.js implementation
const crypto = require('crypto');

function generateApiKey(length = 32) {
    return crypto.randomBytes(length).toString('hex');
}

// Generate 256-bit (32 byte) API key
const apiKey = generateApiKey(32);
console.log(apiKey);
// Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

// Base64 URL-safe encoding
function generateApiKeyBase64(length = 32) {
    return crypto.randomBytes(length)
        .toString('base64')
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=/g, '');
}

const apiKeyBase64 = generateApiKeyBase64(32);
console.log(apiKeyBase64);
// Output: "p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"

// Browser implementation (Web Crypto API)
function generateApiKeyBrowser(length = 32) {
    const array = new Uint8Array(length);
    crypto.getRandomValues(array);
    return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}

How it works in JavaScript

Node.js uses the built-in crypto.randomBytes() method which provides cryptographically secure random data. For browsers, crypto.getRandomValues() fills a typed array with random values. Both methods are suitable for generating API keys with sufficient entropy for production use.

Sample output

Hexadecimal: a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
Base64 URL-safe: p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo
Browser: c4e8f2a9d6b7e3f1a8c5d9b2e6f4a7c1d8b3e9f6a2c7d5b1e4f8a3c9d6b7e2f5

JavaScript notes

  • Node.js 15.7+ supports crypto.randomBytes(32).toString('base64url'), which removes the three replace() calls.
  • In the browser function, crypto is the global Web Crypto object; generate production keys on the server, not in client code.
  • crypto.timingSafeEqual(a, b) throws when the buffers differ in length, so compare fixed-length hashes rather than raw input.

API Key Generation Code Examples in Python

Generate cryptographically secure API keys in Python using the secrets module. The secrets module is specifically designed for security-critical applications like API key generation.

import secrets
import base64

def generate_api_key(length=32):
    """Generate hexadecimal API key."""
    return secrets.token_hex(length)

# Generate 256-bit (32 byte) API key
api_key = generate_api_key(32)
print(api_key)
# Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

def generate_api_key_base64(length=32):
    """Generate base64 URL-safe API key."""
    return secrets.token_urlsafe(length)

api_key_base64 = generate_api_key_base64(32)
print(api_key_base64)
# Output: "p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"

# Generate with prefix for versioning
def generate_versioned_api_key(prefix="sk", length=32):
    """Generate API key with prefix (e.g., sk_live_, sk_test_)."""
    token = secrets.token_urlsafe(length)
    return f"{prefix}_{token}"

versioned_key = generate_versioned_api_key("sk_live", 32)
print(versioned_key)
# Output: "sk_live_p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"

How it works in Python

Python's secrets module provides three convenient functions: token_hex() for hexadecimal encoding, token_urlsafe() for Base64 URL-safe encoding, and token_bytes() for raw bytes. The token_urlsafe() function is particularly useful as it automatically handles URL-safe encoding without manual replacement of special characters.

Sample output

Hexadecimal: a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
Base64 URL-safe: p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo
With prefix: sk_live_p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo

Python notes

  • secrets.token_hex(32) returns 64 characters and secrets.token_urlsafe(32) 43; the argument is bytes, not characters.
  • Store hashlib.sha256(key.encode()).hexdigest() and compare with hmac.compare_digest().
  • The prefix in generate_versioned_api_key is not random; the 32 bytes after it carry all the strength.

API Key Generation Code Examples in Java

Generate cryptographically secure API keys in Java using SecureRandom for enterprise applications. Suitable for Spring Boot, microservices, and RESTful APIs.

import java.security.SecureRandom;
import java.util.Base64;

public class ApiKeyGenerator {
    private static final SecureRandom random = new SecureRandom();

    public static String generateApiKey(int length) {
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);

        // Convert to hexadecimal
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static String generateApiKeyBase64(int length) {
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);

        // Base64 URL-safe encoding
        return Base64.getUrlEncoder()
                     .withoutPadding()
                     .encodeToString(bytes);
    }

    public static void main(String[] args) {
        // Generate 256-bit (32 byte) API key
        String apiKey = generateApiKey(32);
        System.out.println("Hex: " + apiKey);
        // Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

        String apiKeyBase64 = generateApiKeyBase64(32);
        System.out.println("Base64: " + apiKeyBase64);
        // Output: "p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"
    }
}

How it works in Java

Java's SecureRandom class provides cryptographically strong random number generation. The implementation uses Base64.getUrlEncoder().withoutPadding() for URL-safe encoding without padding characters. This approach is thread-safe and suitable for high-concurrency enterprise applications.

Sample output

Hexadecimal: a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
Base64 URL-safe: p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo

Java notes

  • One static SecureRandom is thread-safe and avoids reseeding cost on every call.
  • Java 17+ HexFormat.of().formatHex(bytes) replaces the String.format loop, which is slow for many keys.
  • Compare with MessageDigest.isEqual(), which is constant-time, not String.equals().

API Key Generation Code Examples in C#

Generate cryptographically secure API keys in C# using RandomNumberGenerator for ASP.NET Core and .NET applications. Perfect for Web APIs and microservices.

using System;
using System.Security.Cryptography;

public class ApiKeyGenerator
{
    public static string GenerateApiKey(int length = 32)
    {
        using var rng = RandomNumberGenerator.Create();
        byte[] bytes = new byte[length];
        rng.GetBytes(bytes);

        // Convert to hexadecimal
        return BitConverter.ToString(bytes).Replace("-", "").ToLower();
    }

    public static string GenerateApiKeyBase64(int length = 32)
    {
        using var rng = RandomNumberGenerator.Create();
        byte[] bytes = new byte[length];
        rng.GetBytes(bytes);

        // Base64 URL-safe encoding
        return Convert.ToBase64String(bytes)
                      .Replace('+', '-')
                      .Replace('/', '_')
                      .TrimEnd('=');
    }

    public static void Main()
    {
        // Generate 256-bit (32 byte) API key
        string apiKey = GenerateApiKey(32);
        Console.WriteLine($"Hex: {apiKey}");
        // Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

        string apiKeyBase64 = GenerateApiKeyBase64(32);
        Console.WriteLine($"Base64: {apiKeyBase64}");
        // Output: "p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"
    }
}

How it works in C#

C#'s RandomNumberGenerator class provides cryptographically secure random byte generation. The implementation properly disposes of the RNG with using statements. For .NET 6+, you can use RandomNumberGenerator.GetBytes() static method for cleaner code. The Base64 URL-safe encoding manually replaces special characters.

Sample output

Hexadecimal: a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
Base64 URL-safe: p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo

C# notes

  • .NET 6+ has RandomNumberGenerator.GetBytes(32), a static call with nothing to dispose.
  • Convert.ToHexString() (.NET 5+) replaces BitConverter.ToString().Replace(); .NET 9 adds Convert.ToHexStringLower() and Base64Url.EncodeToString().
  • Compare with CryptographicOperations.FixedTimeEquals() and hash with SHA256.HashData().

API Key Generation Code Examples in C++

Generate cryptographically secure API keys in C++ using modern C++11/14/17 random facilities. Suitable for native applications, game servers, and embedded systems.

#include <iostream>
#include <random>
#include <string>
#include <vector>
#include <sstream>
#include <iomanip>

class ApiKeyGenerator {
private:
    std::random_device rd;

public:
    std::string generateApiKey(size_t length = 32) {
        std::vector<unsigned char> bytes(length);

        // Generate random bytes
        for (size_t i = 0; i < length; ++i) {
            bytes[i] = static_cast<unsigned char>(rd() % 256);
        }

        // Convert to hexadecimal
        std::stringstream ss;
        ss << std::hex << std::setfill('0');
        for (unsigned char byte : bytes) {
            ss << std::setw(2) << static_cast<int>(byte);
        }

        return ss.str();
    }
};

int main() {
    ApiKeyGenerator generator;

    // Generate 256-bit (32 byte) API key
    std::string apiKey = generator.generateApiKey(32);
    std::cout << "API Key: " << apiKey << std::endl;
    // Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

    return 0;
}

How it works in C++

Modern C++ provides std::random_device for accessing hardware entropy sources. This implementation generates random bytes and converts them to hexadecimal representation using std::stringstream. For production use with higher security requirements, consider using OpenSSL or Crypto++ libraries for cryptographically secure random generation.

Sample output

API Key: a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
API Key: c4e8f2a9d6b7e3f1a8c5d9b2e6f4a7c1d8b3e9f6a2c7d5b1e4f8a3c9d6b7e2f5
API Key: b9f5a3c8e2d7f4a1b6e9c3d8f7a2b5e1c6d9f4a7b3e8c2d6f1a9b4e7c5d3f8a6

C++ notes

  • The standard lets std::random_device be deterministic; prefer OpenSSL RAND_bytes(buf, 32) (returns 1 on success) or libsodium randombytes_buf().
  • rd() % 256 is unbiased because random_device returns full 32-bit values, but it wastes three bytes of every call.
  • Wipe key buffers after use with OPENSSL_cleanse() or sodium_memzero(); a plain loop may be optimized away.

API Key Generation Code Examples in Ruby

Generate cryptographically secure API keys in Ruby using SecureRandom. Perfect for Rails APIs, Sinatra applications, and Ruby microservices.

require 'securerandom'

class ApiKeyGenerator
  def self.generate(length: 32)
    # Hexadecimal encoding (64 characters for 32 bytes)
    SecureRandom.hex(length)
  end

  def self.generate_base64(length: 32)
    # Base64 URL-safe encoding
    SecureRandom.urlsafe_base64(length)
  end

  def self.generate_with_prefix(prefix: "sk_live", length: 32)
    # Generate with version prefix
    token = SecureRandom.urlsafe_base64(length)
    "#{prefix}_#{token}"
  end
end

# Generate 256-bit (32 byte) API key
api_key = ApiKeyGenerator.generate(length: 32)
puts api_key
# Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

# Base64 URL-safe encoding
api_key_base64 = ApiKeyGenerator.generate_base64(length: 32)
puts api_key_base64
# Output: "p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"

# With prefix for identification
versioned_key = ApiKeyGenerator.generate_with_prefix(prefix: "sk_live", length: 32)
puts versioned_key
# Output: "sk_live_p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"

How it works in Ruby

Ruby's SecureRandom module provides convenient methods for API key generation. SecureRandom.hex() generates hexadecimal strings, while SecureRandom.urlsafe_base64() generates Base64 URL-safe strings without padding. Both methods use the operating system's cryptographically secure random number generator.

Sample output

Hexadecimal: a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
Base64 URL-safe: p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo
With prefix: sk_live_p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo

Ruby notes

  • SecureRandom.hex(n) and SecureRandom.urlsafe_base64(n) take bytes; urlsafe_base64 omits padding by default.
  • In Rails, has_secure_token generates Base58 tokens on a model column; compare secrets with ActiveSupport::SecurityUtils.secure_compare.
  • Store Digest::SHA256.hexdigest(key) instead of the key itself.

API Key Generation Code Examples in Go

Generate cryptographically secure API keys in Go using crypto/rand for microservices and backend systems. Idiomatic Go implementation with proper error handling.

package main

import (
    "crypto/rand"
    "encoding/base64"
    "encoding/hex"
    "fmt"
)

// GenerateAPIKey generates a hexadecimal API key
func GenerateAPIKey(length int) (string, error) {
    bytes := make([]byte, length)
    if _, err := rand.Read(bytes); err != nil {
        return "", fmt.Errorf("failed to generate API key: %w", err)
    }
    return hex.EncodeToString(bytes), nil
}

// GenerateAPIKeyBase64 generates a base64 URL-safe API key
func GenerateAPIKeyBase64(length int) (string, error) {
    bytes := make([]byte, length)
    if _, err := rand.Read(bytes); err != nil {
        return "", fmt.Errorf("failed to generate API key: %w", err)
    }
    return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString(bytes), nil
}

func main() {
    // Generate 256-bit (32 byte) API key
    apiKey, err := GenerateAPIKey(32)
    if err != nil {
        panic(err)
    }
    fmt.Println("Hex:", apiKey)
    // Output: "a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9"

    // Base64 URL-safe encoding
    apiKeyBase64, err := GenerateAPIKeyBase64(32)
    if err != nil {
        panic(err)
    }
    fmt.Println("Base64:", apiKeyBase64)
    // Output: "p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo"
}

How it works in Go

Go's crypto/rand package provides cryptographically secure random byte generation using the operating system's CSPRNG. The implementation uses proper error handling with wrapped errors. base64.URLEncoding.WithPadding(base64.NoPadding) creates URL-safe encoding without padding characters, which is ideal for API keys used in URLs.

Sample output

Hexadecimal: a7f3e9c2d8b4f1a6e5c9d7b3f8a2e6c4d9b5f7a3e8c6d2b9f4a7e1c5d8b3f6a9
Base64 URL-safe: p3_pwr2L8RpuXJbT-IouaztX86jG0rmU9KfhxdizNpo

Go notes

  • base64.RawURLEncoding is the same as URLEncoding.WithPadding(base64.NoPadding), written shorter.
  • Go 1.24 adds rand.Text(), a 26-character Base32 string with at least 128 random bits, and rand.Read no longer returns errors.
  • Hash with sha256.Sum256 and compare with subtle.ConstantTimeCompare.

Try the Interactive Generator

Need values right now rather than code? The API key generator runs in the browser and exports to TXT, CSV or JSON.

OPEN THE API KEY GENERATOR →