GeneratePass
CRYPTOGRAPHIC SECRET GENERATOR

Secret Token Generator

Generate cryptographically secure API keys, JWT secrets, and encryption keys.

Token Type API Key
Length 32 bytes
Security Details

How secret generation works

All secrets are generated using the Web Crypto API's crypto.getRandomValues() function, which provides cryptographically secure random numbers. No data ever leaves your browser.

Fundamentals

What Are Secret Tokens?

A secret token is a randomly generated string of characters used to authenticate users, authorize API requests, secure sessions, and validate form submissions. Unlike passwords, tokens are not chosen by humans — they are produced by cryptographic random number generators to ensure maximum entropy and unpredictability. Every token in a secure system serves one or more of these purposes: proving identity, granting access, or verifying that a request came from a legitimate source.

In modern web development, tokens are everywhere. When you log into a website, a session token is created and stored in a cookie so the server knows who you are on subsequent requests. When a mobile app calls a backend API, it sends an API key in the header to identify itself. When a user submits a form, a CSRF token ensures the request originated from your site, not a malicious one. Each of these scenarios relies on a token that must be generated with cryptographically secure randomness — otherwise, an attacker could predict or guess the token and impersonate a legitimate user.

The key difference between a secret token and a password is that tokens are never meant to be memorable. They are raw entropy — long, random strings that no human could type from memory. This is actually their strength: because they are not derived from words, patterns, or personal information, they are resistant to dictionary attacks, social engineering, and brute-force guessing. A well-generated 32-byte token has 256 bits of entropy, which means an attacker would need to try approximately 1.16 × 10^77 possible values to guess it — a number larger than the estimated atoms in the observable universe.

Token Taxonomy

Token Types and Their Uses

Not all tokens serve the same purpose. Understanding the different types helps you choose the right length, format, and security practices for your use case.

API Keys

Length: 32–64 bytes (256–512 bits) · Format: Hex or alphanumeric

API keys identify the calling application, not the user. They are typically long-lived and sent in request headers. Because they travel over the network, they must be transmitted over HTTPS only. Common prefixes like sk_live_ or ak_ help identify key type in logs but do not reduce security — the entropy is in the random portion. Store API keys in environment variables, never in source code.

JWT Signing Secrets

Length: 32–64 bytes (256–512 bits) · Format: Hex or Base64

A JWT secret is used to sign and verify JSON Web Tokens server-side. Unlike API keys, this secret never leaves the server — clients only see the signed token. If the secret is compromised, an attacker can forge arbitrary JWTs and impersonate any user. Use HS256 with a 256-bit secret minimum, or switch to RS256 asymmetric signing for better security. Rotate JWT secrets regularly and use automated key rollover to avoid downtime.

Session Tokens

Length: 32–64 bytes (256–512 bits) · Format: Hex, Base64, or URL-safe

Session tokens are temporary credentials issued after successful authentication. They are stored in cookies (preferably HttpOnly, Secure, and SameSite) and have a limited lifetime. Because sessions grant full account access, they must be unguessable. OWASP recommends at least 128 bits of entropy. Invalidate sessions on logout, after password changes, and after periods of inactivity.

CSRF Tokens

Length: 16–32 bytes (128–256 bits) · Format: Hex or Base64

Cross-Site Request Forgery tokens are embedded in forms and verified on submission to ensure the request originated from your site. They can be per-session (tied to the user's session) or per-request (unique for each form submission). CSRF tokens do not need to be as long as API keys because they are validated server-side and never stored in databases. 128 bits provides adequate protection against prediction attacks.

OAuth State and Nonce Values

Length: 16–32 bytes (128–256 bits) · Format: Hex or URL-safe Base64

OAuth state parameters prevent CSRF during the authorization flow. They are generated before redirecting to the provider and validated when the user returns. A nonce (number used once) prevents replay attacks in OpenID Connect. Both must be cryptographically random, stored temporarily, and validated exactly once. Shorter tokens are acceptable here because they are single-use and time-limited.

Webhook Secrets

Length: 32–64 bytes (256–512 bits) · Format: Hex

Webhook secrets are used to verify that incoming webhook payloads actually came from the expected source. Services like Stripe, GitHub, and Slack sign their webhook payloads with a shared secret. The recipient recomputes the signature and compares it. Use HMAC-SHA256 with a random 256-bit secret for webhook verification. Store the secret securely and never expose it in client-side code.

Best Practices

How to Generate Secure Tokens

Generating a secure token requires more than just creating a random string. The source of randomness, the encoding, and the handling of the token all matter. Here are the principles every developer should follow:

Use a CSPRNG, Not Math.random()

The Web Crypto API's crypto.getRandomValues() is a cryptographically secure pseudo-random number generator. JavaScript's Math.random() is deterministic and predictable. In Node.js, use crypto.randomBytes(). In Python, use secrets.token_hex(). In Go, use crypto/rand. Never roll your own randomness.

Generate Before You Need

Create tokens during account creation, deployment, or configuration — not at runtime on every request. Pre-generated tokens can be stored securely and reused consistently. This also makes token rotation predictable and auditable.

Use Enough Entropy

Minimum 128 bits for CSRF tokens, 256 bits for API keys and session tokens, 256+ bits for JWT signing secrets. In practice, 32 bytes (256 bits) is a safe default for most token types. Entropy is measured in bits, not characters — a 32-byte hex token has exactly 256 bits of entropy regardless of the encoding.

Choose the Right Encoding

Hex encoding is universal and safe for most contexts. Base64 is more compact but contains +, /, and = which may need escaping. URL-safe Base64 replaces these with -, _ and strips padding. Alphanumeric encoding avoids all special characters but is slightly less space-efficient.

Transmit Over TLS Only

A token transmitted over an unencrypted connection can be intercepted by anyone on the network. Always enforce HTTPS. Set the Secure flag on cookies containing tokens, use HTTP-only to prevent JavaScript access, and add SameSite=Strict or Lax to prevent CSRF.

Rotate Tokens Regularly

Even secure tokens should be rotated on a schedule. API keys every 90 days, session secrets annually, and JWT signing secrets whenever there is a personnel change or suspected compromise. Implement zero-downtime rotation by supporting both old and new keys during the transition window.

Reference Guide

Token Length Recommendations

The right token length depends on the use case, the threat model, and the encoding format. The table below provides minimum recommendations based on OWASP guidelines and industry best practices.

Token Type Min Length Recommended Entropy (bits)
API Key 32 bytes 32–64 bytes 256–512
JWT Signing Secret 32 bytes 32–64 bytes 256–512
Session Token 32 bytes 32–64 bytes 256–512
CSRF Token 16 bytes 16–32 bytes 128–256
OAuth State / Nonce 16 bytes 16–32 bytes 128–256
Webhook Secret 32 bytes 32–64 bytes 256–512
Encryption Key (AES-256) 32 bytes 32 bytes 256

Why 256 bits is the standard: AES-256, the gold standard for symmetric encryption, uses a 256-bit key. The same entropy level is appropriate for tokens because it provides a security margin that is computationally infeasible to brute-force with current or foreseeable hardware. Even a quantum computer using Grover's algorithm would still need 2^128 operations to crack a 256-bit token — a task that remains impractical.

Security Anti-Patterns

Common Token Security Mistakes

Even developers who understand cryptography can make mistakes in how tokens are generated, stored, and used. These are the most common vulnerabilities seen in production systems:

Using Predictable Tokens

Generating tokens with timestamps, sequential IDs, or Math.random() makes them guessable. An attacker who knows the generation pattern can predict the next token. The March 2024 Sisense breach was caused by a leaked secret that was used to sign data pipeline tokens — if that token had been properly rotated, the impact would have been contained. Always use a CSPRNG and never expose the generation logic to clients.

Logging Tokens in Plaintext

Application logs, access logs, and error reports are common exfiltration vectors. If a token appears in a log file, an attacker who gains access to that log gains access to the token. Mask tokens in logs — show only the last 4 characters. Use structured logging with redaction middleware to automatically strip sensitive values before they reach log storage.

Hardcoding Tokens in Source Code

Tokens committed to Git repositories — even private ones — are a critical risk. Automated scanners continuously monitor GitHub for leaked secrets. Use environment variables, secret managers (Vault, AWS Secrets Manager, Doppler), or encrypted configuration files. Never place tokens in client-side code, JavaScript bundles, or Dockerfiles.

Storing Tokens Without Encryption

Database columns containing tokens should be encrypted at rest. Plaintext token storage in SQL databases means a single SQL injection vulnerability exposes every token in the system. Use envelope encryption or a dedicated secrets vault. Consider hashing tokens with a slow hash (bcrypt/Argon2) if you only need to verify possession, not retrieve the original value.

Reusing Tokens Across Environments

Using the same JWT secret or API key in development, staging, and production means a compromise in any environment affects all of them. Generate unique tokens for each environment. Development tokens should be clearly labeled (e.g., dev_ prefix) and never used in production systems.

Not Implementing Token Revocation

Without a revocation mechanism, a compromised token remains valid until it naturally expires. Implement token blacklisting (using a short-lived cache like Redis), short expiration times, and automatic rotation. For JWTs, use a jti (JWT ID) claim and maintain a revocation list checked on every request.

Common Questions

Frequently Asked Questions

A secret token is a randomly generated string used to authenticate users, authorize API requests, secure sessions, and validate CSRF protections. Tokens serve as digital credentials that prove identity or entitlement without exposing sensitive data like passwords. They are generated using cryptographically secure random number generators and should never be guessable or predictable.

Most tokens should be at least 256 bits (32 bytes) for cryptographic security. JWT secrets need 256+ bits, API keys typically need 32–64 bytes, session tokens need 32–64 bytes, and CSRF tokens need 128–256 bits. Shorter tokens are vulnerable to brute-force attacks. When in doubt, 32 bytes is a safe default for nearly all token types.

API keys are opaque identifiers sent with every request to authenticate the caller. They are long-lived and must travel over the network, so they are vulnerable to interception if TLS is not enforced. JWT secrets are used to sign and verify JSON Web Tokens server-side — they never leave the server. API keys identify who is calling; JWT secrets prove the token is genuine. If a JWT secret is compromised, an attacker can forge arbitrary tokens for any user.

No. Math.random() uses a deterministic algorithm (typically xorshift128+) that produces predictable sequences. If an attacker observes a few outputs, they can seed their own PRNG and predict all future values. This makes tokens generated with Math.random() vulnerable to reconstruction attacks. Always use crypto.getRandomValues() in browsers, crypto.randomBytes() in Node.js, or the secrets module in Python.

Rotate tokens on a regular schedule — API keys every 90 days, session secrets at least annually, and JWT signing secrets when team members leave or a compromise is suspected. Automated rotation with zero-downtime key rollover is the gold standard. Support both old and new keys during a transition window to avoid service disruptions.

Hex encoding is the most universal and compatible — it produces only characters 0–9 and a–f with no special characters. Base64 is more compact but may contain +, /, or = characters that need escaping in URLs. URL-safe Base64 replaces those with -, _, and strips padding. Alphanumeric encoding is safest for systems that only accept letters and digits, but is slightly less space-efficient. Choose based on your system's character restrictions.

Fundamentals

What is a Secret Token Generator?

A secret token generator creates cryptographically secure random strings used for authentication, API keys, session tokens, JWT signing secrets, and encryption keys. Unlike regular random strings, secret tokens are specifically designed for security applications where unpredictability is critical. A weak or predictable token can compromise entire systems.

Our generator uses the Web Crypto API to produce cryptographically secure random bytes, then encodes them in your preferred format (hex, Base64, or alphanumeric). Each token type has specific requirements for length and character set to ensure adequate security for its intended purpose.

Technical Deep Dive

How Secret Token Generation Works

Our generator uses crypto.getRandomValues() to produce random bytes, then converts them to the selected format. The entropy of a token is determined by its length and character set. For example, a 32-character hex token has 128 bits of entropy (32 x 4 bits per hex character).

API Keys: Typically 32-64 bytes encoded in hex or Base64. These authenticate API requests and must be unpredictable to prevent unauthorized access.

JWT Secrets: HMAC signing keys for JSON Web Tokens. These should be at least 256 bits (32 bytes) to prevent signature forgery.

Session Tokens: Random strings that identify user sessions. These must be unpredictable to prevent session hijacking attacks.

Practical Applications

Where Secret Tokens Are Used

API Authentication: Services like GitHub, Stripe, and AWS use secret tokens to authenticate API requests. These tokens prove the caller's identity and authorize access to protected resources.

JWT Signing: JSON Web Tokens use HMAC or RSA keys to sign payloads. The signing key must be secret and unpredictable to prevent token forgery.

OAuth Client Secrets: OAuth 2.0 uses client secrets to authenticate applications requesting access to user data. These secrets must be kept confidential and generated with sufficient randomness.

Webhook Signatures: Services sign webhook payloads with secret keys so recipients can verify authenticity. The shared secret must be cryptographically random.

Security Pitfalls

Secret Token Security Mistakes

Using Short Tokens: Tokens shorter than 128 bits (16 bytes hex) can be brute-forced. Always use at least 256 bits (32 bytes hex) for high-security applications like JWT signing and API keys.

Hardcoding Tokens: Never embed secret tokens in source code, configuration files, or client-side JavaScript. Use environment variables or secret management services.

Logging Tokens: Secret tokens should never appear in logs, error messages, or debugging output. Configure logging frameworks to filter sensitive data.

Reusing Tokens: Each API, service, or environment should use its own unique token. If one token is compromised, reusing it across services exposes all of them.

Related Tools

Related Cryptographic Tools

Explore these related cryptographic generation tools:

Frequently Asked Questions

How long should a secret token be?
For most applications, 32 bytes (256 bits) provides excellent security. API keys should be 32-64 bytes. JWT signing secrets should be at least 32 bytes (256 bits). Session tokens should be 32-64 bytes. Avoid tokens shorter than 16 bytes (128 bits).
Should I use hex or Base64 for my token?
Hex is more readable and debugging-friendly, making it good for API keys. Base64 is more compact and URL-safe, making it good for tokens that appear in URLs. Both provide the same security when generated with sufficient length.
Can secret tokens be regenerated?
Yes, but regenerating tokens invalidates all existing sessions and API integrations. Generate new tokens periodically as a security best practice, and have a rotation plan to minimize service disruption.
How should I store secret tokens?
Use environment variables, secret management services (AWS Secrets Manager, HashiCorp Vault), or encrypted configuration files. Never store tokens in plain text, source code, or version control systems. Rotate tokens if they are accidentally exposed.
What is the difference between a token and a password?
Passwords are memorized by humans and typically have lower entropy. Tokens are machine-generated, have higher entropy, and are stored (not memorized). Tokens are used for programmatic authentication (APIs, webhooks), while passwords are used for human authentication.