HS256 (HMAC SHA-256) JWT Signing
Understand HS256 (HMAC SHA-256) for JWT signing, how symmetric key signing works, when to choose HS256, and key management considerations.
Detailed Explanation
HS256 (HMAC using SHA-256) is the most commonly used symmetric signing algorithm for JWTs. It uses a single shared secret key to both create and verify the token signature. The algorithm applies HMAC (Hash-based Message Authentication Code) with SHA-256 as the underlying hash function to the base64url-encoded header and payload.
How HS256 signing works:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
The signing process concatenates the encoded header and payload with a period separator, then computes the HMAC-SHA256 of this string using the secret key. The resulting signature is base64url-encoded and appended as the third part of the JWT. Verification repeats the same computation and compares the result to the received signature.
Key requirements:
The HS256 secret must be at least 256 bits (32 bytes) long to match the security level of SHA-256. Using shorter keys weakens the algorithm. The key should be generated using a cryptographically secure random number generator, not derived from a password or passphrase. Weak secrets like "mysecretkey" can be brute-forced, completely compromising all tokens signed with that key.
Symmetric key trade-offs:
The fundamental characteristic of HS256 is that the same key signs and verifies. This means every service that needs to verify tokens must possess the secret key. In a microservices architecture with 20 services, all 20 must have access to the signing key. If any single service is compromised, an attacker can forge tokens for the entire system. This is HS256's primary limitation compared to asymmetric algorithms like RS256.
When to choose HS256:
HS256 is ideal when a single server or a small, tightly controlled cluster both issues and verifies tokens. It is simpler to implement, faster to compute, and produces smaller signatures than RSA-based alternatives. Monolithic applications, internal tools, and single-server APIs are excellent candidates. For distributed systems where token issuers and consumers are separate entities, consider RS256 or ES256 instead.
Use Case
A single-server Node.js application uses HS256 with a 256-bit secret to sign session JWTs, keeping the implementation simple and verification fast.