---
title: "JWT Secret Generator: HS256, HS384 and HS512 Keys"
description: "Generate a random JWT secret sized for HS256, HS384 or HS512 as base64url, base64 or hex, with a JWT_SECRET .env line. Runs in your browser, never sent."
image: "https://cdn.sethserver.com/blog-images/jwt-secret-generator-social-1789657093.webp"
---

# JWT Secret Generator: HS256, HS384 and HS512 Keys

Your JWT secret

generating...

.env line

JWT\_SECRET=

Algorithm (sets the key size)

Output format

Changing the format re-encodes the same bytes, so you can compare. Changing the algorithm makes a new secret. Everything happens in your browser.

I have lost count of the JWT tutorials that tell you to set `JWT_SECRET=secret` and move on. This page does the boring part properly: it pulls the right number of random bytes for the algorithm you picked and hands them to you in the encoding your config wants. The rest of the page is about the parts that bite later, mostly how your library reads that string.

## What a JWT secret actually does

HS256, HS384 and HS512 are HMAC with SHA-256, SHA-384 and SHA-512. The server takes the token header and payload, runs them through HMAC with the secret, and appends the result as the signature. To verify, it does the same computation and compares.

The consequence: whoever can verify a token can also create one. The secret is not a lock on one door, it is the master key to your whole auth system. Anyone who has it can mint a token that says `"sub": "admin"` and your API will believe it.

## How long should a JWT secret be?

RFC 7518, section 3.2, is short and clear about it: *"A key of the same size as the hash output (for instance, 256 bits for HS256) or larger MUST be used with this algorithm."* That is what the algorithm dropdown above does.

| Algorithm | Hash | Minimum key | base64url chars | base64 chars | hex chars |
| --- | --- | --- | --- | --- | --- |
| HS256 | SHA-256 | 32 bytes | 43 | 44 | 64 |
| HS384 | SHA-384 | 48 bytes | 64 | 64 | 96 |
| HS512 | SHA-512 | 64 bytes | 86 | 88 | 128 |

Two details matter here. First, the requirement is about bits of real randomness, not string length. `correct-horse-battery-staple-2024` is 33 characters, so it passes a naive length check, and it has a tiny fraction of 256 bits of entropy. Second, going far past the minimum does not help. RFC 2104 says HMAC hashes any key longer than the hash block size first (64 bytes for SHA-256, 128 bytes for SHA-384 and SHA-512), and a random key the size of the output is already beyond brute force.

Recent PyJWT releases (2.11.0 and later) check this for you and emit an `InsecureKeyLengthWarning` when an HMAC key has fewer bytes than the hash output. I tested it: a 31 byte key with HS256 warns, 32 bytes is quiet. You can make it an error with the `enforce_minimum_key_length` option. In my testing jsonwebtoken 9 and jose 6 accepted a 5 byte HMAC key without complaint, so do not count on your library to save you.

## Raw string or decoded bytes? Pick one and write it down

This is the bug that eats an afternoon. The generator gives you a string like `q3Jf...`. That string is an encoding of 32 random bytes. Your code can hand the library either the string itself or the decoded bytes, and those are two different HMAC keys.

Here is how the popular libraries treat what you give them:

- **PyJWT**: a `str` key is encoded to UTF-8 bytes, a `bytes` key is used as is. So `os.environ["JWT_SECRET"]` means the 43 ASCII bytes of the string, not the 32 bytes it encodes.
- **jsonwebtoken** (Node): the README says a string secret is UTF-8 encoded. If you want the decoded bytes, it tells you to pass `Buffer.from(secret, 'base64')`.
- **jose** (Node, browsers, Deno, Bun): it will not take a plain string for HS256 at all. You pass a `Uint8Array`, which you get from either `new TextEncoder().encode(secret)` (the string's bytes) or `jose.base64url.decode(secret)` (the decoded bytes).

Both approaches are secure with a secret from this page. The 43 character base64url string is 43 bytes long and carries all 256 bits of entropy, so using it raw still clears the RFC 7518 minimum. What breaks things is mixing: a Python service that signs with the raw string and a Node service that verifies with `Buffer.from(secret, 'base64')` will reject every token, and the error message will just say the signature is invalid.

My default is the raw string everywhere, because every language and every config system can pass a string without anyone thinking about it. If you decode, decode everywhere. These pairs all produce the same key and verify each other's tokens:

```
# Python (PyJWT): string used as UTF-8 bytes
import os, jwt
secret = os.environ["JWT_SECRET"]
token = jwt.encode({"sub": "42"}, secret, algorithm="HS256")
claims = jwt.decode(token, secret, algorithms=["HS256"])

// Node (jsonwebtoken): same thing
const jwt = require('jsonwebtoken');
const secret = process.env.JWT_SECRET;
const claims = jwt.verify(token, secret, { algorithms: ['HS256'] });

// Node (jose): same thing, spelled out
import { jwtVerify } from 'jose';
const key = new TextEncoder().encode(process.env.JWT_SECRET);
const { payload } = await jwtVerify(token, key, { algorithms: ['HS256'] });
```

And the decoded version, if that is the convention you chose:

```
# Python: decode base64url (add back the padding first)
import base64, os
s = os.environ["JWT_SECRET"]
key = base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))   # 32 bytes for HS256

// jsonwebtoken ('base64' in Node also accepts the URL-safe alphabet)
const key = Buffer.from(process.env.JWT_SECRET, 'base64');

// jose
import { base64url } from 'jose';
const key = base64url.decode(process.env.JWT_SECRET);
```

If you picked hex, the decoded form is `bytes.fromhex(s)` in Python and `Buffer.from(s, 'hex')` in Node.

## Where the secret goes

The copy button above gives you a line like `JWT_SECRET=...`. base64url and hex only use characters that are safe unquoted in a `.env` file and in a shell. Standard base64 can contain `+`, `/` and `=`, which most dotenv parsers handle fine, but base64url avoids the question entirely, which is why it is the default here.

- **Local development**: a `.env` file that is in `.gitignore`. Check that it actually is.
- **Production**: your platform's secret store (AWS Secrets Manager, Google Secret Manager, Vault, Kubernetes Secrets, Docker secrets, your CI's encrypted variables) injected as an environment variable.
- **One secret per environment**. If staging and production share a secret, a token minted on staging works on production.
- **One secret per purpose**. Do not reuse your JWT secret as your session secret, your CSRF key or your password reset signing key. For those, see the [secret key generator](https://www.sethserver.com/security/secret-key-generator.html) or the [Flask secret key generator](https://www.sethserver.com/security/flask-secret-key-generator.html).
- **Never in frontend code**. If the browser has the HMAC secret, so does everyone who opens dev tools. If a client needs to verify tokens, that is a job for an asymmetric algorithm.

## Generate a JWT secret yourself

If your rule is that production secrets are generated on the server that uses them, good rule. Each of these reads from the operating system's CSPRNG. Swap 32 for 48 (HS384) or 64 (HS512).

```
# OpenSSL
openssl rand -hex 32
openssl rand -base64 32
openssl rand -base64 32 | tr '+/' '-_' | tr -d '='      # base64url

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

# Python 3
python3 -c "import secrets; print(secrets.token_urlsafe(32))"
python3 -c "import secrets; print(secrets.token_hex(32))"

# Straight into a .env file
echo "JWT_SECRET=$(openssl rand -hex 32)" >> .env
```

Note that `secrets.token_urlsafe(32)` takes a byte count, not a character count, so it returns 43 characters.

## Why short or human-chosen secrets get cracked

A JWT carries its own test case. The header and payload are right there in plain base64url, and the signature is HMAC of those with your secret. An attacker who gets hold of a single token (from a log, a browser, a proxy, a screenshot in a bug report) can guess secrets on their own hardware and check each guess against that signature. No rate limit, no lockout, nothing in your logs.

hashcat supports this directly as hash mode 16500, and there are other tools built just for it. Dictionary words, the placeholder secrets from tutorials, company names with a year on the end and short strings are all well within reach. Once the secret is found, the attacker signs whatever claims they like.

A secret of 256 random bits is a different story. There is no pattern for a wordlist to find, and trying every key is not a realistic plan on any hardware. That is the whole argument for generating the secret instead of typing it.

## HS256 vs RS256, ES256 and EdDSA

HMAC is simple and fast, and it is the right choice when the issuer and the verifier are the same application. It gets awkward the moment another service needs to verify tokens, because that service now holds a key that can also create them.

Asymmetric algorithms split the job. The issuer signs with a private key and everyone else verifies with the public key, which can be published at a JWKS endpoint. Use one when:

- several services verify tokens and only one should issue them,
- third parties (customers, partners, mobile apps) need to verify your tokens,
- you run an OpenID Connect or OAuth provider, or
- you want a leaked verifier config to be harmless.

Your options: **RS256** (RSA with SHA-256; RFC 7518 requires a key of 2048 bits or larger), **PS256** (RSA-PSS), **ES256** (ECDSA on P-256, small signatures), and **EdDSA** with Ed25519 (RFC 8037). RFC 9864 has since registered `Ed25519` as a fully specified `alg` value and deprecated the polymorphic `EdDSA` name, so check which one your libraries accept before you pick. RS256 has the widest support if you are unsure. Generate keys with OpenSSL:

```
# RSA (RS256 / PS256)
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out private.pem

# P-256 (ES256)
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out private.pem

# Ed25519
openssl genpkey -algorithm ed25519 -out private.pem

# Public key for any of them
openssl pkey -in private.pem -pubout -out public.pem
```

In Python, PyJWT needs the `cryptography` package for these (`pip install "pyjwt[crypto]"`). Whatever you pick, pin it on the verifying side, which is the next section.

## Rotating a JWT secret with kid

If you swap the secret in one step, every outstanding token dies and everyone is logged out. Sometimes that is exactly what you want (the secret leaked). For routine rotation, use the `kid` header:

1. Give each secret an ID, like `2026-09`, and keep a small map of ID to secret.
2. Sign new tokens with the newest secret and put its ID in the `kid` header.
3. When verifying, read `kid` from the header, look up that secret, and reject unknown IDs.
4. Once the longest-lived token signed with the old secret has expired (refresh tokens included), delete the old secret.

```
# PyJWT
import jwt

SECRETS = {"2026-09": new_secret, "2026-03": old_secret}
CURRENT = "2026-09"

token = jwt.encode(claims, SECRETS[CURRENT], algorithm="HS256",
                   headers={"kid": CURRENT})

def verify(token):
    kid = jwt.get_unverified_header(token).get("kid")
    if kid not in SECRETS:
        raise jwt.InvalidTokenError("unknown kid")
    return jwt.decode(token, SECRETS[kid], algorithms=["HS256"])

// jose: jwtVerify accepts a function that picks the key from the header
import { jwtVerify } from 'jose';
const enc = new TextEncoder();
const secrets = { '2026-09': enc.encode(newSecret), '2026-03': enc.encode(oldSecret) };

const { payload } = await jwtVerify(token, async (header) => {
  if (!Object.hasOwn(secrets, header.kid)) throw new Error('unknown kid');
  return secrets[header.kid];
}, { algorithms: ['HS256'] });
```

The header is untrusted input until the signature checks out, so `kid` should only ever select from keys you already hold. Never use it as a file path or a database query fragment.

## Mistakes I keep seeing

- **Not pinning the algorithm.** Always pass the allowed list (`algorithms=["HS256"]` in PyJWT, `algorithms: ['HS256']` in jsonwebtoken and jose). PyJWT 2 refuses to decode without it, which is the right call.
- **A placeholder secret that shipped.** `changeme`, `secret` and the value from the README all end up in production eventually. Fail at startup if the secret is missing or shorter than the table above.
- **Tokens that live forever.** Set `exp`. Short access tokens plus refresh tokens make both rotation and leaks less painful.
- **Secrets in the repo.** Once a secret is in git history, treat it as public and rotate it. Deleting the file does not help.
- **Logging whole tokens.** Every logged HS256 token is an offline cracking target and a replayable credential until it expires.

For the broader picture, I wrote up [my opinionated security best practices](https://www.sethserver.com/security/seths-opinionated-security-best-practices.html) and a piece on [least privilege](https://www.sethserver.com/ai/principle-of-least-privilege-in-the-ai-age.html). If what you actually need is a credential for other people to call your API, JWT is often the wrong tool; use the [API key generator](https://www.sethserver.com/security/api-key-generator.html) and store only a hash.

## Frequently asked questions

How long should a JWT secret be?

At least as long as the hash output of the algorithm, which RFC 7518 section 3.2 makes a MUST: 32 bytes (256 bits) for HS256, 48 bytes (384 bits) for HS384 and 64 bytes (512 bits) for HS512. Those bytes need to be random. A 32 character password typed by a human is 32 bytes long but nowhere near 256 bits of entropy.

Should I base64-decode the secret or use the string as it is?

Either works, as long as every service that signs or verifies tokens does the same thing. PyJWT and jsonwebtoken turn a string key into its UTF-8 bytes, so the 43 character base64url string becomes a 43 byte key. If one service decodes the secret and another does not, signatures will never match. Pick one convention and write it down next to the env var.

Can I use a password or a passphrase as my JWT secret?

Please do not. Anyone holding a single token can test guesses against its signature offline, as fast as their hardware allows, and tools like hashcat support JWTs directly. A human-chosen secret falls to a wordlist. Use random bytes from a CSPRNG, like the ones this page generates.

Should I use HS256 or RS256?

Use HS256 when the same service (or a small set of services you fully trust) both issues and verifies tokens. Use an asymmetric algorithm such as RS256, ES256 or Ed25519 when verifiers should not be able to mint tokens: separate microservices, third parties, or anything that fetches your public keys from a JWKS endpoint.

Is a secret longer than the minimum more secure?

Not really. HMAC hashes any key longer than the hash block size (64 bytes for SHA-256, 128 bytes for SHA-384 and SHA-512) down first, and a random key the size of the hash output is already out of brute-force range. Longer does no harm, it just does not buy you anything.

What happens to existing tokens when I change the JWT secret?

Every token signed with the old secret fails verification, so everyone gets logged out and refresh tokens stop working. To rotate without that, put a `kid` (key ID) in the token header, sign new tokens with the new key, and keep accepting the old key until the longest-lived token signed with it has expired.

Is the secret generated on this page sent anywhere?

No. The secret comes from your browser's crypto.getRandomValues and the page does not send it anywhere. You can watch the network tab while you click regenerate. If your policy says production secrets never touch a browser, run one of the openssl, Node or Python one-liners on this page on the machine that needs the secret.

Related tools: [API key generator](https://www.sethserver.com/security/api-key-generator.html), [secret key generator](https://www.sethserver.com/security/secret-key-generator.html), [encryption key generator](https://www.sethserver.com/security/encryption-key-generator.html), [Flask secret key generator](https://www.sethserver.com/security/flask-secret-key-generator.html), and the [strong random password generator](https://www.sethserver.com/security/strong-random-password-generator.html).

-Sethers


```json
{"@context": "https://schema.org", "@graph": [{"@type": "WebApplication", "applicationCategory": "DeveloperApplication", "author": {"@type": "Person", "name": "Seth Black", "url": "https://www.sethserver.com/"}, "description": "Generate random HMAC secrets for HS256, HS384 and HS512 JSON Web Tokens, sized to RFC 7518, as base64url, base64 or hex, with a ready JWT_SECRET line for your .env file. Runs in your browser.", "name": "JWT Secret Generator", "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "operatingSystem": "Web", "url": "https://www.sethserver.com/security/jwt-secret-generator.html"}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "acceptedAnswer": {"@type": "Answer", "text": "At least as long as the hash output of the algorithm, which RFC 7518 section 3.2 makes a MUST: 32 bytes (256 bits) for HS256, 48 bytes (384 bits) for HS384 and 64 bytes (512 bits) for HS512. Those bytes need to be random. A 32 character password typed by a human is 32 bytes long but nowhere near 256 bits of entropy."}, "name": "How long should a JWT secret be?"}, {"@type": "Question", "acceptedAnswer": {"@type": "Answer", "text": "Either works, as long as every service that signs or verifies tokens does the same thing. PyJWT and jsonwebtoken turn a string key into its UTF-8 bytes, so the 43 character base64url string becomes a 43 byte key. If one service decodes the secret and another does not, signatures will never match. Pick one convention and write it down next to the env var."}, "name": "Should I base64-decode the secret or use the string as it is?"}, {"@type": "Question", "acceptedAnswer": {"@type": "Answer", "text": "Please do not. Anyone holding a single token can test guesses against its signature offline, as fast as their hardware allows, and tools like hashcat support JWTs directly. A human-chosen secret falls to a wordlist. Use random bytes from a CSPRNG, like the ones this page generates."}, "name": "Can I use a password or a passphrase as my JWT secret?"}, {"@type": "Question", "acceptedAnswer": {"@type": "Answer", "text": "Use HS256 when the same service (or a small set of services you fully trust) both issues and verifies tokens. Use an asymmetric algorithm such as RS256, ES256 or Ed25519 when verifiers should not be able to mint tokens: separate microservices, third parties, or anything that fetches your public keys from a JWKS endpoint."}, "name": "Should I use HS256 or RS256?"}, {"@type": "Question", "acceptedAnswer": {"@type": "Answer", "text": "Not really. HMAC hashes any key longer than the hash block size (64 bytes for SHA-256, 128 bytes for SHA-384 and SHA-512) down first, and a random key the size of the hash output is already out of brute-force range. Longer does no harm, it just does not buy you anything."}, "name": "Is a secret longer than the minimum more secure?"}, {"@type": "Question", "acceptedAnswer": {"@type": "Answer", "text": "Every token signed with the old secret fails verification, so everyone gets logged out and refresh tokens stop working. To rotate without that, put a kid (key ID) in the token header, sign new tokens with the new key, and keep accepting the old key until the longest-lived token signed with it has expired."}, "name": "What happens to existing tokens when I change the JWT secret?"}, {"@type": "Question", "acceptedAnswer": {"@type": "Answer", "text": "No. The secret comes from your browser's crypto.getRandomValues and the page does not send it anywhere. You can watch the network tab while you click regenerate. If your policy says production secrets never touch a browser, run one of the openssl, Node or Python one-liners on this page on the machine that needs the secret."}, "name": "Is the secret generated on this page sent anywhere?"}]}]}
{"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [{"@type": "ListItem", "position": 1, "name": "sethserver", "item": "https://www.sethserver.com/"}, {"@type": "ListItem", "position": 2, "name": "Tools", "item": "https://www.sethserver.com/tools/"}, {"@type": "ListItem", "position": 3, "name": "JWT Secret Generator: HS256, HS384 and HS512 Keys", "item": "https://www.sethserver.com/security/jwt-secret-generator.html"}]}
```
