JWT secret length: 32 bytes is 64 hex characters or 43 Base64URL characters
A service that signs a token with a 32-byte key and a service that verifies it with the same secret can still return JsonWebTokenError: invalid signature. The secret itself can be identical β the difference is the repres
A service that signs a token with a 32-byte key and a service that verifies it with the same secret can still return JsonWebTokenError: invalid signature. The secret itself can be identical β the difference is the representation. One side holds 64 hex characters, the other holds 43 Base64URL characters, and the verifying side decodes those 43 characters back to 32 bytes while the signing side uses the 43 characters themselves as the key. Same secret on paper, different bytes on the wire.
The rule that decides this is written in bytes, and the numbers most people quote are characters. This post covers what RFC 7518 Β§3.2 actually requires, how 32 bytes turn into 64 or 43 characters, how to generate a correct key in Node, Python and OpenSSL, the three places where a byte count silently changes, and how to read the five errors [email protected] throws when the two sides disagree.
What the RFC actually requires
A key of the same size as the hash output (for instance, 256 bits for "HS256") or larger MUST be used with this algorithm.
β RFC 7518, section 3.2
That sentence is the entire requirement. HS256 signs with SHA-256, whose output is 256 bits, so the HMAC key must be at least 256 bits β 32 bytes. HS384 requires 48 bytes and HS512 requires 64, for the same reason.
The sizes are a floor, not a target. HMAC's security is bounded by the key, so a 16-byte random key with HS256 leaves the hash at 256 bits but caps the search at 2^128, and candidates can be tested offline against a token the attacker already has. A 64-byte key with HS256 is allowed and adds no strength over 32 bytes: the signature cannot be stronger than the 256-bit hash, and HMAC reduces a key longer than its block size before using it. Generate the size that matches the algorithm and stop. jsonwebtoken will sign with a 16-byte secret without complaint, so the RFC minimum is only enforced if your configuration code enforces it.
Everything here applies to the HMAC family. RS256 and ES256 sign with a private key and verify with a public key; their sizes come from the RSA modulus or the elliptic curve, not from this 32/48/64-byte rule.
32 bytes in characters
A byte is eight bits. A hex character carries four, so two characters per byte. A Base64URL character carries six, and Base64 writes three bytes as four characters; Base64URL drops the = padding, so 32 bytes become 43 characters. That gives three lengths for the same three keys:
- HS256: 32 bytes β 64 hex characters β 43 Base64URL characters
- HS384: 48 bytes β 96 hex characters β 64 Base64URL characters
- HS512: 64 bytes β 128 hex characters β 86 Base64URL characters
Standard Base64 uses the same six-bit mapping but keeps = padding and uses + and / where Base64URL uses - and _. The same keys are 44, 64 and 88 characters. Three encodings, one byte count.
Figure 1 β One 32-byte key, three valid encodings. RFC 7518 Β§3.2 sets the floor in bytes, not characters.
The comparison that matters: 32 hex characters are 16 bytes, half the HS256 minimum, while 32 random ASCII letters and digits are 32 bytes and clear the length rule with about 190 bits of entropy instead of 256. When someone says a secret is "32 characters", ask which encoding: the same phrase describes a key that is half the minimum and a key that meets it exactly. Only generated bytes give you the length and the entropy in one step.
Generate the bytes, then encode
The safest habit is to generate 32 random bytes and hand the raw bytes to the library. Node's CSPRNG returns a Buffer; encoding is only for storage.
const crypto = require('node:crypto');
const jwt = require('jsonwebtoken');
const secret = crypto.randomBytes(32); // 32 bytes = HS256 minimum
console.log(secret.toString('hex').length); // 64
console.log(secret.toString('base64url').length); // 43
const token = jwt.sign({ sub: 'demo-user' }, secret, { algorithm: 'HS256', expiresIn: '15m' });
const claims = jwt.verify(token, secret, { algorithms: ['HS256'] });
console.log(claims.sub); // demo-user
Both sides use the same Buffer, so there is nothing to decode and nothing to disagree about. Reading the secret from the environment and failing at boot is covered in the Node.js JWT secret guide.
Python's PyJWT signs with the bytes you pass and does not decode Base64URL for you:
import secrets, time, jwt
secret = secrets.token_urlsafe(32) # 43 chars, Base64URL without padding
key = secret.encode() # the 43 text bytes, used as the HMAC key
token = jwt.encode({"sub": "demo-user", "exp": int(time.time()) + 900}, key, algorithm="HS256")
print(len(secret), jwt.decode(token, key, algorithms=["HS256"])["sub"]) # 43 demo-user
That passes as long as every service treats the 43 characters as the key. It fails the moment one service decodes the value back to 32 bytes. Pick one convention: use secrets.token_bytes(32) and pass those bytes everywhere, or store the 43-character text and decode it explicitly with base64.urlsafe_b64decode(secret + "=" * (-len(secret) % 4)) on every side that needs bytes. The Python JWT secret guide covers the same encoding choices with the PyJWT details.
OpenSSL needs no runtime:
# 32 random bytes as hex: 64 characters
openssl rand -hex 32
# 32 random bytes as standard Base64: 44 characters, one '=' of padding
openssl rand -base64 32
# capture the value without the trailing newline
JWT_SECRET="$(openssl rand -hex 32)"
Both commands produce 32 random bytes; the first writes them in hex, the second in Base64. $(...) strips the newline; redirecting to a file and reading it back does not.
Where the byte count quietly changes
Human strings. secret.length in JavaScript counts UTF-16 code units, not bytes and not code points. "ε―ι₯π".length is 4; Buffer.byteLength("ε―ι₯π", "utf8") is 10. A validation such as if (secret.length < 32) throw is therefore neither a byte check nor an entropy check: it passes 16 emoji (64 UTF-8 bytes) but rejects a 12-character Chinese phrase (36 bytes) that technically clears the byte floor and is still guessable. Length and randomness are separate requirements.
Whitespace from files. openssl rand -hex 32 > secret.txt writes 64 characters and a newline. fs.readFileSync("secret.txt", "utf8") returns 65 bytes, so the service reading the file and the service reading the environment variable sign with different keys. Trim values that come from files, and do not hard-wrap secrets in config stores.
Decoders that never throw. Buffer.from(value, "base64url") does not validate its input. A 42-character string with 32 valid characters and 10 invalid ones decodes to 24 bytes without an error; a 31-character hex string decodes to 15 bytes; aabb!ccdd as hex decodes to 2 bytes. A value with a stray space, a URL-encoded %, or a truncated copy still "works" β with a different key. If your app decodes Base64URL, the cheap check is a round trip:
node -e "const v=process.argv[1]; const b=Buffer.from(v,'base64url'); console.log(b.length, b.toString('base64url')===v)" "$JWT_SECRET"
If the re-encoded string does not equal the input, the value is not canonical Base64URL. That catches dropped characters, the wrong alphabet and accidental truncation in one line.
The five errors jsonwebtoken 9.0.3 throws
Exact messages, quoted from jsonwebtoken 9.0.3:
| Exact message | What it means | First thing to check |
|---|---|---|
Error: secretOrPrivateKey must have a value |
sign or verify received undefined or an empty string. |
The variable never loaded: misspelled name, missing .env, empty deploy value. |
JsonWebTokenError: invalid signature |
The signature does not match the key bytes this process used. | Same encoding on both sides, no trailing whitespace, no key rotation. |
TokenExpiredError: jwt expired |
exp is in the past at the verifier. |
Compare exp with now in seconds; check both clocks and the signing lifetime. |
JsonWebTokenError: jwt malformed |
The token is not three dot-separated Base64URL segments. |
split(".").length === 3; check a leftover Bearer prefix, truncation, whitespace. |
JsonWebTokenError: invalid algorithm |
The token's alg is rejected by verify. |
Decode the header, print alg, align the algorithms list with the signer. |
Triage in this order
Decode before you debug. jwt.decode(token) splits and decodes the three segments without checking the signature, so it tells you whether the problem is the token or the key. If the token does not split into three parts, it is jwt malformed and the secret is irrelevant. If it decodes, read alg and exp first: an alg you did not sign with explains invalid algorithm, and an exp in the past explains jwt expired. Only when the token parses, the algorithm matches and the expiry is in the future is the key the suspect.
Two more details. expiresIn takes seconds as a number and a time-span string such as "15m"; a numeric string like "15" is read as milliseconds, so the token expires immediately. And invalid algorithm is not only about asymmetric tokens: an explicit algorithms: ["HS256"] list rejects an HS512 token, a mismatch you created in the verify call.
For invalid signature, compare bytes and not text. During a deploy, print a truncated SHA-256 of the key bytes on each service: it is enough to see whether they match, and it does not put the secret itself into logs. If the fingerprints differ, one side is decoding, trimming or reading a different variable. If they match, check that you are verifying the token you think you are; a cached header or a test fixture from an earlier login is a common way to get this error with a correct secret. Tokens that worked before a rotation fail because the retired key is gone, not because of its length.
A five-minute self-check
Run these in order. Each one passes or points at a specific file.
Figure 2 β The same seven checks as a card, in the order I run them.
- Count bytes in the form the library sees. Plain text:
printf %s "$JWT_SECRET" | wc -c. Hex or Base64URL: decode first and check the result β 32 bytes for HS256, 48 for HS384, 64 for HS512. - Write the encoding down next to the variable. If one service decodes Base64URL, every service decodes it; a comment saying which representation is stored prevents the next person from "fixing" the value into a mismatch.
- Fail at boot. Read and validate the secret at startup and throw if it is missing or shorter than the algorithm's floor.
secretOrPrivateKey must have a valueshould never reach a request log. - Trim what comes from files. Remove leading and trailing whitespace, and keep the padding if the value is standard Base64.
- Compare fingerprints, not secrets. During a deploy, print a truncated SHA-256 of the key bytes on each service and remove the line when they match.
- Check both clocks. Run
date -uon the signer and the verifier; clock skew larger than the token lifetime producesjwt expiredon fresh tokens. - Keep the previous key during a rotation. Verify against the current key and the previous one while old tokens are still valid, then retire the old key after the longest token lifetime.
The same numbers, the generation commands and the encoding conversions are collected on the JWT secret length page. I maintain the free browser-based generator behind it; it takes the key length in bytes, keeps the same bytes when you switch between Hex and Base64URL, and warns when the length is below the algorithm's RFC minimum.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.
