The Golden Rule of RFC 7518 (Section 3.2)
RFC 7518 explicitly dictates: "A key of the same size as the hash output (for instance, 256 bits for "HS256") or larger MUST be used with this algorithm." This is not an optional suggestion. For HMAC-SHA256, the minimum acceptable secret length is 256 bits (32 bytes). Using a shorter key violates the security guarantees of the underlying HMAC construction.
Using a secret shorter than the hash output size exposes your authentication system to offline dictionary attacks and rainbow table matching.
Entropy vs. String Length: The Common Misconception
Many developers confuse character length with cryptographic entropy. A 32-character string composed of common dictionary words ("MySecretCompanyTokenKey2026!") does NOT possess 256 bits of entropy. True entropy comes from drawing each byte uniformly from a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).
Required Key Lengths by HMAC Algorithm
Here is the definitive specification matrix for HMAC algorithms defined in JSON Web Algorithms (JWA):
• **HS256 (HMAC with SHA-256)**: Minimum 256 bits (32 raw bytes, 64 Hex characters, 43–44 Base64 characters).
• **HS384 (HMAC with SHA-384)**: Minimum 384 bits (48 raw bytes, 96 Hex characters, 64 Base64 characters).
• **HS512 (HMAC with SHA-512)**: Minimum 512 bits (64 raw bytes, 128 Hex characters, 86–88 Base64 characters).
Any key below these thresholds reduces cryptographic margins and may cause modern JWT libraries to throw runtime validation warnings or exceptions.
Frequently Asked Questions
Can I use a 128-bit key for HS256?
Technically the math works, but it strictly violates RFC 7518 Section 3.2. Modern security audit tools and linters will flag 128-bit keys as a critical security vulnerability.
Does a Base64-encoded secret provide more security than Hex?
No. Base64 and Hex are simply representation encodings. The underlying entropy is strictly determined by the number of random bytes (e.g., 32 bytes = 256 bits), regardless of how it is serialized.