HS512 (HMAC-SHA512)
HS512 is the strongest widely supported symmetric JWT algorithm in RFC 7518, combining HMAC with the SHA-512 hash function. Like HS256 and HS384, it uses a single shared secret for both signing and verification, making it straightforward to implement in monoliths and internal APIs. HS512 requires a 512-bit (64-byte) secret to align with the hash block size and produces a 512-bit signature digest. It appears in high-assurance environments, regulated industries, and compliance frameworks that explicitly mandate SHA-512 for message authentication. For most SaaS and consumer web applications, HS256 remains the pragmatic default; HS512 is the choice when policy, defense-in-depth, or organizational standards demand the largest SHA-2 family hash for HMAC-based JWT signing.
Last updated July 25, 2026
How It Works
HS512 signing follows the standard JWS compact format. The header declares {"alg":"HS512","typ":"JWT"}, the payload carries your claims, and both segments are Base64url-encoded and concatenated with a dot. Your signing service computes HMAC-SHA512 over that string using the 512-bit shared secret as key material. SHA-512 processes data in 1024-bit blocks; using a secret at least 512 bits long ensures the HMAC key matches the hash design parameters recommended by RFC 7518. The resulting 64-byte digest becomes the signature segment after Base64url encoding. Verifiers decode the token, confirm the alg header matches HS512, recompute HMAC-SHA512 with the same secret, and validate the signature with a timing-safe compare. Beyond signature checks, production verifiers must enforce exp, nbf, aud, and iss claims to prevent replay and scope violations. Libraries expose HS512 as an explicit algorithm constant — jsonwebtoken uses 'HS512', PyJWT uses algorithm='HS512', and golang-jwt uses jwt.SigningMethodHS512. Performance overhead versus HS256 is modest on modern hardware; the bigger operational cost is managing a longer secret and ensuring every service in the fleet supports the algorithm before rollout. Prefer HS512 only when a written policy or auditor explicitly requires SHA-512 HMAC; otherwise standardize on HS256 with a 256-bit CSPRNG secret to keep operations simpler. Always pin algorithms: ["HS512"] on verify and reject tokens that advertise a different alg. Store the 64-byte secret outside source control and rotate it with a grace period when staff with secret access leave.
When to Use
Deploy HS512 when compliance or internal security baselines require SHA-512 for HMAC, when you operate in regulated sectors that document algorithm choices explicitly, or when defense-in-depth justifies maximum symmetric hash strength. It suits high-security internal APIs, government-adjacent systems, and platforms where security reviewers expect SHA-512 by name in the JWT header.
When Not to Use
Skip HS512 for typical consumer-facing APIs where HS256 meets all practical security needs with simpler 256-bit secrets. Avoid it when third-party verifiers cannot access your signing secret — choose RS256 or PS256 for asymmetric verification. Do not select HS512 merely for longer tokens or perceived marketing security; the operational burden of 512-bit secret management rarely pays off outside mandated environments.
Key Length Requirements
Generate a minimum 512-bit (64-byte) secret for HS512 — 128 hexadecimal characters. This matches the SHA-512 output size and satisfies RFC 7518 key-length guidance. Never promote an existing HS256 256-bit secret to HS512 without generating fresh random material. Use CSPRNG output, store in a secrets manager, and plan rotation with kid header support if multiple secrets coexist during rollover.
Security Pitfalls
- Reusing an HS256-sized 256-bit secret with HS512 violates RFC 7518 key-length recommendations and weakens the HMAC construction.
- Omitting algorithm pinning at verification allows downgrade attacks if verifiers accept HS256, HS384, and HS512 interchangeably.
- Assuming HS512 alone satisfies compliance while storing secrets in plaintext env files or git history fails audit requirements.
- Ignoring token expiration and audience validation after a valid signature lets stolen tokens work until expiry across unintended services.
- Deploying HS512 to some microservices while others still expect HS256 causes silent auth failures during rolling migrations.
Code Examples
Node.js — sign and verify HS512
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const secret = crypto.randomBytes(64).toString('hex'); // 512-bit
const token = jwt.sign(
{ sub: 'admin-7', role: 'admin' },
secret,
{ algorithm: 'HS512', expiresIn: '10m', issuer: 'auth.example.com' }
);
const claims = jwt.verify(token, secret, {
algorithms: ['HS512'],
issuer: 'auth.example.com',
});
console.log(claims.role);Python — sign and verify HS512
import secrets
import jwt
from datetime import datetime, timedelta, timezone
secret = secrets.token_hex(64) # 512-bit key
now = datetime.now(timezone.utc)
token = jwt.encode(
{
"sub": "admin-7",
"role": "admin",
"iss": "auth.example.com",
"exp": now + timedelta(minutes=10),
},
secret,
algorithm="HS512",
)
claims = jwt.decode(
token,
secret,
algorithms=["HS512"],
issuer="auth.example.com",
)
print(claims["role"])Go — sign and verify HS512
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
func main() {
key := make([]byte, 64)
_, _ = rand.Read(key)
secret := hex.EncodeToString(key)
token := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.MapClaims{
"sub": "admin-7",
"role": "admin",
"iss": "auth.example.com",
"exp": time.Now().Add(10 * time.Minute).Unix(),
})
tokenString, _ := token.SignedString([]byte(secret))
parsed, _ := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
if t.Method != jwt.SigningMethodHS512 {
return nil, fmt.Errorf("unexpected alg: %v", t.Header["alg"])
}
return []byte(secret), nil
})
fmt.Println(parsed.Valid)
}Generate Keys
Recommended: 512-bit
Open Jwt Secret GeneratorRelated Comparisons
Related Terms
Related Guides
Frequently Asked Questions
Is HS512 overkill for a startup API?
For most startups, yes. HS256 with a 256-bit random secret provides more than adequate security. Choose HS512 only when a compliance auditor or security policy explicitly requires SHA-512 HMAC.
How much slower is HS512 compared to HS256?
Benchmarks vary by hardware, but HMAC-SHA512 typically adds microseconds per operation. For API authentication, network and database latency dwarf the difference. Profile only if you sign millions of tokens per second.
Can I use the same secret for HS256 and HS512?
Do not share secrets across algorithms. If you must support both during migration, use separate secrets with distinct kid values and sunset the weaker algorithm quickly. Never verify both with one undifferentiated key without explicit routing logic.
What hex length confirms a 512-bit secret?
A 512-bit secret encoded as hex is 128 characters. If your secret string is 64 hex characters, that is only 256 bits — sufficient for HS256 but not for HS512. Regenerate before going to production.
Does HS512 affect refresh token strategies?
The signing algorithm does not change refresh token architecture, but high-security deployments pairing HS512 often also enforce short access token TTLs (5–15 minutes) and rotate refresh tokens on each use. Align token lifetimes with your threat model regardless of hash choice.
Can I reuse an HS256 secret for HS512?
No. RFC 7518 requires a key at least as long as the hash output, so HS512 needs 512 bits. Reusing a 256-bit HS256 secret under-provisions the key and may be rejected by strict libraries. Generate a dedicated 512-bit secret and treat environments separately.
Looking for a short definition?
Glossary: HS512 (HMAC-SHA512)