You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jsonwebtoken npm包生成的令牌最大长度是多少?

JWT Refresh Token Maximum Hex Length: Why It’s Longer Than 64 Characters

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 jsonwebtoken is {"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 is 15 + 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 + N is divisible by 3: ((15 + N) / 3) * 4 characters
      • If there’s a remainder of 1: (((15 + N) // 3) * 4) + 2 characters
      • If remainder is 2: (((15 + N) // 3) *4) +3 characters
  • 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=270 bytes → encoded to (270/3)*4=360 characters
    • Full JWT length: 81+360=441 → hex length: 441*2=882 characters
  • For 1000-character usernames:
    • Raw payload JSON length: 15+1000=1015 bytes → encoded to (1015//3)*4 +2=1354 characters
    • Full JWT length: 81+1354=1435 → hex length: 1435*2=2870 characters

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 12:30:22