Join our Newsletter — 33% off our NHI Course
Home› Guides› HS256 vs RS256: Choosing a JWT Signing Algorithm…
Guide Authentication

HS256 vs RS256: Choosing a JWT Signing Algorithm Safely

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 14 November 2026 17 min read
On this page

HS256 and RS256 both produce a valid JWT signature, but they put the power to mint tokens in very different places: with HS256 every party that can verify a token can also forge one, while with RS256 only the holder of the private key can sign. That single difference drives key distribution, rotation, blast radius after a leak and the algorithm confusion attacks that still appear in token libraries. This guide compares the two, adds ES256, PS256 and EdDSA, and covers OpenID Connect, service-to-service calls and non-human identity issuers, for engineers and identity architects choosing a signing design. For the full validation checklist, read the JWT Security Guide first; this page goes deeper on the algorithm decision only.

Key takeaways

  • The real choice is trust topology: HS256 is a shared secret, so it fits only when issuer and verifier are the same service or a tightly held trust domain; RS256 and other public-key algorithms fit whenever tokens cross a team, service or organisation boundary.
  • HS256 is secure when the key is: a random key of at least 256 bits, held by few parties, is sound; a human-chosen password as the HMAC key can be brute forced offline from any captured token (RFC 8725 s2.2 and s3.5).
  • Algorithm confusion is a verifier bug, not an algorithm flaw: forging an RS256 token as HS256 with the public key as the HMAC secret works only when the verifier lets the token header pick the routine; binding each key to exactly one algorithm closes it.
  • Public keys make rotation boring: RS256, ES256 and EdDSA publish verification keys in a JWKS with a kid, so rotation needs no secret redistribution; HS256 rotation means a coordinated secret change at every verifier.
  • RS256 is the interoperable default, not the best curve: RS256 is mandatory to support for RFC 9068 access tokens and the default for OpenID Connect ID tokens, while ES256 and EdDSA give smaller, faster signatures where every verifier supports them.

The short answer

Use an asymmetric algorithm (RS256, PS256, ES256 or EdDSA) for any token that one party issues and another party verifies. Use HS256 only where the same component, or a small set of components you operate as one, both signs and verifies, and the key is a random value stored in a secrets manager or KMS. If you are unsure, choose asymmetric: RFC 9068 says the use of asymmetric cryptography is recommended for JWT access tokens because it makes it simpler for resource servers to obtain validation keys.

Whichever you choose, the verifier must fix the expected algorithm per issuer in configuration. RFC 8725 s3.1 states that each key must be used with exactly one algorithm, and that this must be checked when the key is used. Most real HS256 and RS256 incidents come from ignoring that rule, not from the mathematics of either algorithm.

How each algorithm works

HS256: HMAC with SHA-256

The issuer computes an HMAC over the base64url header and payload using a secret key, and the verifier recomputes the HMAC with the same key and compares. RFC 7518 s3.2 requires a key of at least the hash output size (256 bits for HS256) and a constant-time comparison to stop timing attacks. There is no public half: the verification key is the signing key. RFC 7518 s3.1 lists HS256 as Required, which is why it appears in so many quick-start examples.

RS256: RSASSA-PKCS1-v1_5 with SHA-256

The issuer signs with an RSA private key and publishes the public key. Verifiers check the signature with the public key, which cannot be used to sign. RFC 7518 s3.3 requires RSA keys of 2048 bits or larger, and RS256 is listed as Recommended. RFC 7518 s8.3 notes that RFC 3447 advises against PKCS#1 v1.5 signatures for new applications in favour of RSASSA-PSS, and that keys with a low public exponent must not be used.

The asymmetric alternatives

  • PS256: RSASSA-PSS with SHA-256, same key sizes as RS256 (2048 bits or larger, RFC 7518 s3.5), Optional in the JWA table.
  • ES256: ECDSA on P-256 with SHA-256, Recommended+ in RFC 7518 s3.1. Signatures are a fixed 64-octet R and S sequence (s3.4), and verifiers must reject other lengths. ECDSA needs a strong per-signature random value, so sign in a maintained library or KMS.
  • EdDSA: RFC 8037 adds key type OKP and the EdDSA algorithm with Ed25519 and Ed448. Signing is deterministic and needs no random numbers, which removes the ECDSA nonce failure class. Confirm every verifier library, gateway and cloud service in the path supports it before adopting.

Side-by-side comparison

PropertyHS256RS256ES256 / EdDSA
Key typeShared symmetric secret (JWK kty oct)RSA key pair (kty RSA), 2048 bits or moreEC P-256 (kty EC) or OKP Ed25519
Who can mint tokensEvery holder of the key, including every verifierOnly the private key holderOnly the private key holder
Key distributionSecret must be copied to each verifier over a protected channelPublic key published in a JWKS at jwks_uriPublic key published in a JWKS
RotationCoordinated secret change at every verifierAdd new kid, switch signing, retire old key after overlapSame as RS256
Signature size32 bytes256 bytes at 2048 bits64 bytes
JWA requirement (RFC 7518)RequiredRecommendedES256 Recommended+; EdDSA defined in RFC 8037
Main attackOffline brute force of weak keys; any verifier compromise is an issuer compromiseAlgorithm confusion when the verifier trusts alg; private key theftSame as RS256, plus ECDSA nonce misuse for ES256
Best fitSingle service sessions, internal state tokens, one-team systemsFederation, OIDC, multi-service APIs, maximum library supportNew designs wanting compact tokens and fast signing

Threat model: HS256

With HS256 the attacker's goal is the secret, because the secret is both the verifier and the mint. Three paths matter.

  • Offline guessing: anyone who captures one token (from a log, a browser, a proxy capture or a public bug report) can test candidate keys against it without touching your systems. RFC 8725 s2.2 calls out applications that use human-memorable passwords as HS256 keys, and s3.5 says such passwords must not be used directly as HMAC keys. A random 256-bit key makes this path infeasible; a phrase from a tutorial or a framework default does not.
  • Verifier compromise: every service that verifies the token holds the key. A leaked configuration file or container image gives the attacker a full issuer. The blast radius is every service that trusts that key.
  • Secret reuse: the same value used as the HMAC key in several environments, or reused as an OAuth client secret, spreads one leak across systems. OpenID Connect Core 3.1.3.7 validates HS256 ID tokens with the UTF-8 octets of the client_secret, so a weak client secret is a weak signing key, which is why s16.19 requires client secrets to contain enough entropy to generate strong keys.

The ATT&CK technique for the outcome is T1606 Forge Web Credentials: once the key is known, the attacker can produce tokens with any subject, role or audience, then use them as T1550.001 Application Access Token. See the JWT and Session Tokens in Code and Logs Guide.

Threat model: RS256 and other asymmetric algorithms

Public-key algorithms move the crown jewel to one place, the private key at the issuer, and make the verification material safe to publish. The remaining risks are different in kind.

  • Private key theft: a signing key in a file on the issuer host, in a repository or in a backup lets an attacker mint tokens every verifier accepts. RFC 9068 s5 warns that using separate keys for ID tokens and access tokens is not a safeguard, because resource servers accept any key the authorisation server publishes. Keep signing keys in a KMS or HSM so they cannot be exported. See the Signing keys and certificates in breaches page for how stolen keys have been used.
  • Untrusted key sources: header parameters such as jku, x5u and jwk let a token point at its own verification key. RFC 8725 s3.10 says these must not be trusted blindly, that jku and x5u URLs should be allowlisted to prevent server-side request forgery, and that kid must be validated or sanitised to prevent injection. OpenID Connect Core section 2 says ID tokens should not use x5u, x5c, jku or jwk at all.
  • Stale JWKS caches: verifiers that cache a key set forever keep accepting a retired or compromised key. OpenID Connect Core 10.1.1 tells verifiers to re-fetch the jwks_uri when they see an unfamiliar kid, with a rate limit on refetches.

Algorithm confusion: how it works and how to stop it

RFC 8725 s2.1 describes two classic substitutions. In the first, the attacker sets alg to none and strips the signature. In the second, the attacker takes a token meant for RS256, changes alg to HS256, and signs it with HMAC using the issuer's RSA public key as the secret. A verifier that reads alg from the header and passes "the key" to whichever routine the header names will run HMAC with the public key bytes and accept the forgery.

Both share one root cause: untrusted input chooses how trust is checked. They are reasons to configure the verifier properly, not to avoid RS256. RFC 9068 s2.1 forbids none for access tokens outright.

Confusion variantRoot cause in the verifierControlReference
alg set to noneUnsecured tokens acceptedAllowlist per issuer that excludes noneRFC 7518 s3.6; ASVS 5.0 V9.1.2
RS256 changed to HS256One key object passed to any algorithm; public key used as HMAC secretBind each key to exactly one algorithm and key type; never mix MAC and public-key algorithms for one issuerRFC 8725 s2.1, s3.1
Self-supplied key via jwk, jku or x5uKey taken from the token instead of configurationKeys only from pre-configured sources per issuer; allowlist URLsRFC 8725 s3.10; ASVS 5.0 V9.1.3
kid injectionkid used in a file path, query or commandTreat kid as an opaque lookup key into a fixed mapRFC 8725 s3.10
Cross-token substitutionID token accepted as access token, or one service's token at anotherExplicit typ (for example at+jwt), audience checks, mutually exclusive rulesRFC 8725 s3.11, s3.12; RFC 9068 s4

ASVS 5.0 V9.1.2 asks for an algorithm allowlist per context and says it should ideally contain only symmetric or only asymmetric algorithms, not both. If one verifier must accept both (for example during a migration from HS256 to RS256), keep the keys in separate, typed key objects and route by issuer, never by the header alone.

Key distribution and rotation

Publishing asymmetric keys with JWKS

A JWK Set (RFC 7517 s5) is a JSON document with a keys array. Each public key should carry kty, kid, use set to sig, and alg naming its single algorithm. Authorisation servers advertise the set through the jwks_uri metadata field (RFC 8414), which must use HTTPS, and RFC 9068 s4 says resource servers must use the keys the authorisation server provides. The detailed procedure, including overlap periods and emergency rollover, is in the JSON Web Key Sets (JWKS) and Signing Key Rotation Guide.

Rotating HS256 secrets

There is no public channel for an HMAC key. RFC 7517 s9.2 requires symmetric keys to be protected from unintended parties, so a symmetric JWK must never appear in a public jwks_uri. Rotation is a secrets-management task: generate a new random key, deliver it to every verifier through a secrets manager, have verifiers accept both keys selected by kid, switch the issuer to the new key, then remove the old one after the longest token lifetime has passed.

Rotation stepHS256RS256, ES256, EdDSA
Generate new keyRandom 256-bit or larger value in a secrets manager or KMSNew key pair in a KMS or HSM, private key non-exportable
DistributePush the secret to every verifierAdd the public key to the JWKS with a new kid
OverlapVerifiers hold old and new secretsJWKS holds old and new public keys; OIDC Core 10.1.1 suggests keeping recently retired keys for a while
Switch signingIssuer signs with new secretIssuer signs with new private key
RetireDelete old secret everywhere after max token lifetimeRemove old public key from JWKS after max token lifetime plus cache time
Emergency after leakReplace at every verifier at once; expect outagesRemove the key from JWKS; verifiers refetch on unknown kid or cache expiry

Where each algorithm fits: decision guidance

ScenarioRecommendedWhy
Single web application signing its own session or CSRF state tokenHS256 with a KMS-held random keyIssuer and verifier are the same code; smallest token; no distribution
OAuth authorisation server issuing access tokens to many APIsRS256, PS256 or ES256 via JWKSRFC 9068 recommends asymmetric and requires RS256 support
OpenID Connect ID tokensRS256 (the default) or the client's registered id_token_signed_response_algOIDC Core 3.1.3.7; HS256 only for confidential clients, never public clients (s10.1)
Microservices calling each other through a gatewayAsymmetric issuer, verification at gateway and servicesA compromised service must not be able to mint tokens for others
Client authentication to a token endpointprivate_key_jwt rather than client_secret_jwtNo shared secret at the server; see the JWT Client Authentication (private_key_jwt) Guide
High-volume, constrained or mobile clientsES256 or EdDSA64-byte signatures and fast signing, if every verifier supports them

Small organisations: RS256 works everywhere, and a managed identity provider runs the private key and JWKS for you. Large organisations: standardise on one or two asymmetric algorithms across issuers, put every signing key in a KMS or HSM, and treat any HS256 use across a service boundary as an exception that needs approval. RFC 8725 s3.2 requires cryptographic agility, and NIST IR 8547 (final, October 2026) sets out the transition from quantum-vulnerable algorithms, which include RSA and elliptic curve signatures. See the Crypto-Agility Guide.

Non-human identity token issuers

Most JWTs are now issued to and verified by machines: workload identity tokens, Kubernetes projected service account tokens, CI/CD OIDC tokens, SPIFFE JWT-SVIDs and agent-to-tool access tokens. Workload identity federation depends on asymmetric signing: the relying cloud fetches the issuer's JWKS and trusts the signature, so no long-lived secret crosses the boundary. See the Workload Identity Federation Guide and the Kubernetes Service Account Token Guide.

HS256 in machine-to-machine flows usually signals a shared secret pasted into several services' configuration, which behaves like any other static API key: it spreads, it is hard to rotate, and every holder is an issuer. Inventory these as non-human credentials and move them to an asymmetric issuer or to mutual TLS. The mTLS vs Signed Tokens for Service Authentication and X.509 SVIDs vs JWT SVIDs guides cover those choices.

Worked scenario: moving an internal platform from HS256 to ES256

A platform team runs an internal token service that signs HS256 tokens for 14 microservices. All services hold the same never-rotated secret, and an audit finds it in two container images and a CI log.

  1. Contain: treat the secret as compromised. Generate a new random 256-bit HMAC key in the secrets manager, push it to all 14 services, and accept both old and new keys for no longer than the token lifetime (15 minutes here) while the issuer switches. Then remove the old key everywhere.
  2. Design the target: choose ES256 because every service runs a library that supports it and the gateway validates it; keep RS256 as the fallback for one legacy Java service. Create non-exportable key pairs in the cloud KMS.
  3. Publish: expose a JWKS endpoint over HTTPS with each key's kid, use sig and alg.
  4. Dual verify in audit mode: issue tokens signed with both the HMAC key and ES256 under different issuer values, and log, per service, which validation succeeded. Route by issuer, never by alg header, so no verifier ever accepts a mix for one issuer.
  5. Cut over in rings: two low-risk services first, then the rest. Roll back by switching the issuer flag back to HMAC signing; the HMAC key remains available until the final ring passes.
  6. Retire HS256: remove HMAC keys from all verifiers and secrets stores, set the per-issuer allowlist to ES256 (RS256 for the legacy service), and add a test that a token with alg HS256 or none is rejected.

Afterwards no service can mint tokens for another, and the next rotation is a JWKS change rather than a 14-service secret push.

Detection and measurement

  • Log rejections by reason: disallowed alg, bad signature, unknown kid, wrong typ or aud. A burst of alg none or HS256 attempts against an RS256 issuer is probing for confusion; see the JWT Validation Errors Troubleshooting Guide for separating attacks from misconfiguration.
  • Alert on unexpected signing and leaked keys: KMS sign operations from any principal other than the token service, and secret scanner hits for JWT keys in repositories, images and logs.
MetricTarget
Cross-service issuers using a symmetric algorithmZero, or each one an approved exception
Verifiers with an explicit per-issuer algorithm allowlist100%
Signing keys held in a KMS or HSM as non-exportable100% of asymmetric issuers
Signing keys older than the rotation policyZero
Verifiers passing the negative test suite (none, confusion, foreign key)100%, run in CI

Common failure patterns

  • Tutorial secrets in production: an HS256 key copied from sample code or a short memorable phrase, recoverable offline from one token.
  • One key object for every algorithm: the verifier passes the RSA public key to whatever routine the header names, which is the precondition for RS256 to HS256 confusion.
  • HS256 shared across teams: a "temporary" shared secret between services that grows to dozens of holders, any of which can mint tokens for all.
  • Keys from the token: honouring jku, x5u or an embedded jwk instead of a configured key source.
  • Private key on disk: an RS256 PEM file in the issuer's image or repository, which turns a container leak into a forgery capability.

Framework mapping

Control areaOWASP ASVS 5.0NIST SP 800-53 Rev 5Other
Signature or MAC validated before useV9.1.1SC-23 Session AuthenticityCSF 2.0 PR.AA-03
Algorithm allowlist per contextV9.1.2SC-13 Cryptographic ProtectionRFC 8725 s3.1
Keys from trusted pre-configured sourcesV9.1.3SC-12 Cryptographic Key Establishment and ManagementRFC 8725 s3.10
Validity period enforcedV9.2.1SC-23RFC 9068 s4
Signing key and secret lifecycleV9.1.3SC-12, IA-5 Authenticator ManagementCSF 2.0 PR.AA-01
Forged token threatV9.1.1, V9.1.2SC-13, SC-23ATT&CK T1606, T1550.001

Practitioner checklist

  • Every issuer has one documented algorithm and one key source, stored in verifier configuration.
  • Tokens that cross a service or organisation boundary use RS256, PS256, ES256 or EdDSA.
  • Any HS256 key is random, at least 256 bits, held in a secrets manager and known to the fewest possible services.
  • Public clients never use HS256 ID tokens or client_secret-based MACs.
  • Verifiers reject none, mismatched algorithms, self-supplied keys and unknown kid values after one rate-limited refetch.
  • Asymmetric signing keys are non-exportable in a KMS or HSM, 2048-bit or larger for RSA.
  • JWKS entries carry kid, use and alg; no symmetric key appears in a public key set.
  • Negative tests for algorithm confusion run in CI for every verifier.

Standards and references

Related NHI Mgmt Group resources: JWT Security Guide · JWT vs Opaque Tokens · JSON Web Key Sets (JWKS) and Signing Key Rotation Guide · Cryptographic Key Management Guide · Client ID and Client Secret Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 14 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.