jsonwebtoken npm包生成的令牌最大长度是多少?
Your initial assumption about the 64-character hex length only applies to the raw HMAC-SHA256 signature (32 bytes = 64 hex digits). But a full JWT isn’t just the signature—it’s three distinct parts joined by dots, all encoded in Base64URL. Converting this entire string to hex results in a longer value that varies with your username’s length. Here’s the breakdown:
JWT Structure Breakdown
Every JWT has three components:
- Header: The default header for
jsonwebtokenis{"alg":"HS256","typ":"JWT"}, which Base64URL encodes to a fixed 36-character string. - Payload: Your
{username: String}object. This part’s length depends entirely on how long the username is:- The payload JSON is formatted as
{"username":"[your-username]"}, so its raw length is15 + username-length(15 fixed characters plus the username itself). - When Base64URL encoded, each 3 bytes of JSON translates to 4 characters. For a username of length N:
- If
15 + Nis divisible by 3:((15 + N) / 3) * 4characters - If there’s a remainder of 1:
(((15 + N) // 3) * 4) + 2characters - If remainder is 2:
(((15 + N) // 3) *4) +3characters
- If
- The payload JSON is formatted as
- Signature: The HMAC-SHA256 hash of the header and payload joined by a dot. This produces a 32-byte value, which Base64URL encodes to a fixed 43-character string.
Calculating Total Hex Length
The full JWT string length is:36 (header) + 1 (dot) + encoded-payload-length +1 (dot) +43 (signature) = 81 + encoded-payload-length
Since every character in the JWT is an ASCII byte, converting the entire string to hex doubles the length (each byte becomes two hex digits). So the final hex length is:2 * (81 + encoded-payload-length)
Example Maximum Lengths
- For 255-character usernames (common database max):
- Raw payload JSON length:
15 +255=270bytes → encoded to(270/3)*4=360characters - Full JWT length:
81+360=441→ hex length:441*2=882characters
- Raw payload JSON length:
- For 1000-character usernames:
- Raw payload JSON length:
15+1000=1015bytes → encoded to(1015//3)*4 +2=1354characters - Full JWT length:
81+1354=1435→ hex length:1435*2=2870characters
- Raw payload JSON length:
MySQL Storage Recommendation
To prevent truncation, set your column length based on the maximum allowed username length in your system. If you don’t have a strict limit, VARCHAR(3000) will cover usernames up to ~1000 characters. For even longer usernames, use a TEXT type instead.
内容的提问来源于stack exchange,提问作者Anshuman Garg

