How to Generate Secret Keys for Django, Laravel, Rails and JWTs

What app secret keys do, how long they should be, how each framework expects them encoded, and how to generate, store and rotate them safely.

Updated September 29, 2026 6 min read

Use the free Secret Key GeneratorRandom secrets for JWT, Django, Laravel APP_KEY, Rails and .env files

Almost every web framework asks for a secret during setup: Django's SECRET_KEY, Laravel's APP_KEY, Rails' secret_key_base, the signing key for HS256 JSON Web Tokens, or AUTH_SECRET for Auth.js. Tutorials often show a placeholder such as changeme, and that placeholder has a habit of reaching production. When it does, anyone who knows it can forge session cookies and tokens.

This guide explains what these secrets protect, how long and in what format each one should be, how to generate them with a cryptographically secure source, and how to store and rotate them without breaking your users' sessions.

What an application secret does

Framework secrets are usually used as keys for message authentication (HMAC) and sometimes for encryption:

  • Signed cookies and sessions. The server signs a cookie value with the secret. If a user edits the cookie, the signature no longer matches and the server rejects it. Anyone who knows the secret can create valid-looking cookies, for example one that says they are an administrator.
  • JWTs with HS256 or HS512. The token's signature is an HMAC of its header and payload. The same secret signs and verifies, so a leaked secret lets an attacker mint tokens for any user. The guide on creating and signing a JWT shows the structure in detail.
  • Encryption. Laravel's APP_KEY is an AES key used by the encrypter for encrypted cookies and any values your code encrypts. Changing it makes that data unreadable.
  • Password reset links, CSRF tokens and "remember me" cookies. These are often derived from or signed with the same secret.

The strength of all of this rests on the secret being unpredictable and private. Length and randomness give unpredictability; secure storage gives privacy.

How long, and in what format

Strength is measured in bits of entropy. A value drawn from a secure random generator has as many bits as random bytes × 8. As a rule of thumb, 256 bits (32 random bytes) is a comfortable target for signing keys.

Use Typical format Minimum sensible size
JWT HS256 Random bytes, often Base64URL 32 bytes (256 bits)
JWT HS512 Random bytes, often Base64URL 64 bytes (512 bits)
Django SECRET_KEY 50 characters from Django's alphabet 50 characters
Laravel APP_KEY base64: + 32 bytes in Base64 Exactly 32 bytes for AES-256-CBC
Rails secret_key_base 128 hex characters 64 bytes
Generic session secret Hex or Base64 32 bytes

For HMAC-based JWT algorithms, RFC 7518 requires a key at least as long as the hash output, which is where the 32 and 64-byte figures come from.

Encoding does not add strength; it only makes bytes printable. 32 random bytes are 64 hex characters, 44 Base64 characters with padding, or 43 Base64URL characters without padding. All represent the same 256 bits.

Generate a secret in your browser

The Secret Key Generator uses crypto.getRandomValues, the browser's interface to the operating system's secure random generator, and formats the result for the framework you choose.

  1. Open the Secret Key Generator.
  2. Pick a preset under Framework / use: JWT HS256 secret, JWT HS512 secret, Django SECRET_KEY, Laravel APP_KEY, Rails secret_key_base, Flask / FastAPI SECRET_KEY, Auth.js / NextAuth AUTH_SECRET, Express / session cookie secret, or Custom.
  3. For Custom (and presets that allow it), adjust the Length and Encoding: hex, uppercase hex, Base64 or Base64URL without padding.
  4. Check the Entropy and Strength tiles.
  5. Copy the Secret, or copy the Config line, which is ready to paste into a .env or settings file.
  6. Click Regenerate for a new value.

The Laravel preset is fixed at 32 bytes because the default cipher needs exactly that. Nothing is stored or sent; the secret only exists on the page until you leave.

Generating secrets on the command line

Each framework has its own command, and they are perfectly good choices when you have a shell:

# Generic 32-byte secrets
openssl rand -hex 32
openssl rand -base64 32

# Node.js
node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"

# Python
python -c "import secrets; print(secrets.token_urlsafe(32))"

# Framework commands
python -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
php artisan key:generate     # writes APP_KEY to .env
bin/rails secret             # prints a secret_key_base

What you should not use: Math.random(), timestamps, UUIDs from non-cryptographic generators, hashes of the project name, or anything memorable. These can be predicted or brute-forced. The article on how random number generators work explains why ordinary pseudo-random functions are unsuitable for security.

Storing secrets safely

Generating a strong secret is the easy part. Keeping it private is where most leaks happen.

  • Never commit secrets to Git. Not in settings.py, not in config/app.php, not in a "temporary" test file. Git history keeps the value even after you delete it. Add .env to your ignore file; the .gitignore Generator includes a dotenv template for this.
  • Use environment variables or a secrets manager. Read the value from the environment at startup. In production, use your platform's secret store (for example a cloud provider's secrets manager, your CI system's encrypted variables, or Kubernetes secrets with encryption at rest).
  • Use different secrets per environment. Development, staging and production should never share a key, so a leaked laptop .env does not expose production.
  • Limit who can read them. Access to production secrets should be as restricted as access to the production database.
  • Commit an example file instead. A .env.example with empty values documents which variables are needed without exposing any.

If a secret is ever committed or pasted somewhere public, treat it as compromised: generate a new one and rotate, rather than just deleting the commit.

Rotating a secret without chaos

Changing a secret has side effects, so plan it:

  • Sessions and tokens become invalid. Users are logged out, and JWTs signed with the old key fail verification.
  • Encrypted data may become unreadable. With Laravel, anything encrypted with the old APP_KEY cannot be decrypted with the new one. Recent Laravel versions support listing previous keys so old data can still be read during a transition; check the documentation for your version.
  • Use overlap where the framework allows it. Django supports SECRET_KEY_FALLBACKS (from version 4.1) so old signatures keep validating while new ones use the new key. For JWTs, publish a key ID (kid) and accept both keys until old tokens expire.

Frequently asked questions

How long should a JWT secret be?

At least 32 random bytes (256 bits) for HS256 and 64 bytes for HS512, matching the hash output size as RFC 7518 requires. Longer does no harm; shorter weakens the signature.

Is a secret generated in a browser secure?

Yes, provided the page uses crypto.getRandomValues, which draws from the operating system's secure random source, the same one openssl rand relies on. Avoid tools that use Math.random().

Can I use a password as my secret key?

No. Human-chosen passwords have far less entropy than 32 random bytes and are open to dictionary attacks against signed tokens. Always use randomly generated values.

What happens if I change my Django SECRET_KEY?

Sessions, password reset links and other signed values created with the old key stop validating, so users are logged out. Use SECRET_KEY_FALLBACKS for a smoother rotation.

Where should I keep the generated secret?

In an environment variable or a secrets manager, never in source code or a Git repository. Keep a separate secret for each environment.

Try it now: Secret Key Generator

Loading tool…