How to Generate a JWT Secret Key for HMAC Algorithms
JSON Web Tokens (JWT) signed with HMAC algorithms — HS256, HS384, or HS512 — rely on a shared secret key. Anyone who holds that key can both create and verify tokens, so generating a strong secret is critical.
Requirements for a Secure Secret Key
Before generating a key, understand what “secure” means here:
- Length: at minimum 256 bits (32 bytes) for HS256, 384 bits (48 bytes) for HS384, and 512 bits (64 bytes) for HS512. Shorter secrets are trivially brute-forced.
- Randomness: the key must come from a cryptographically secure random number generator (CSPRNG), not
Math.random()or a timestamp. - Secrecy: never hardcode the key in source code. Store it in environment variables or a secret manager.
Generate with OpenSSL
OpenSSL is the most portable way to generate a secret on any UNIX-like system.
Generate a 256-bit (32-byte) secret encoded as base64:
openssl rand -base64 32For HS384 or HS512, increase the byte count to match the digest size:
# HS384 — 48 bytesopenssl rand -base64 48
# HS512 — 64 bytesopenssl rand -base64 64If you prefer a hex-encoded secret:
openssl rand -hex 32Generate with /dev/urandom (Linux / macOS)
/dev/urandom is a kernel-backed CSPRNG — cryptographically secure and available without any dependency.
# base64-encoded, 32 bytesdd if=/dev/urandom bs=32 count=1 2>/dev/null | base64Generate with PowerShell (Windows)
PowerShell’s System.Security.Cryptography.RandomNumberGenerator uses the OS CSPRNG (CNG on Windows).
# 32 bytes = 256 bits, suitable for HS256[Convert]::ToBase64String( [System.Security.Cryptography.RandomNumberGenerator]::GetBytes(32))For HS384 or HS512, replace 32 with 48 or 64.
Use an Online Generator
If you don’t have a terminal handy, you can use our JWT Secret Key Generator to generate a cryptographically secure secret directly in your browser. The key is generated client-side — nothing is sent to any server.
Best Practices
- Never commit secrets to Git. Use
.envfiles (excluded via.gitignore) or a secret manager like AWS Secrets Manager, HashiCorp Vault, or similar. - Rotate secrets regularly. When you rotate, support both the old and new key during a transition window to avoid invalidating all existing tokens at once.
- Use the right algorithm for your threat model. HMAC is fine for single-party systems where the same service signs and verifies. For distributed systems where multiple services verify tokens without being able to issue them, prefer asymmetric algorithms like RS256 or ES256 — see our guide on JWT signing algorithms.
- Validate your JWT implementation. Once your service is signing tokens, use VulnAPI to check that your implementation correctly rejects tampered tokens and is not vulnerable to known JWT attacks such as the
alg: nonebypass.