RSA Keys for JWT Signing (RS256)
Learn how to use RSA keys for JWT signing with the RS256 algorithm. Understand the difference between HS256 and RS256 and when asymmetric JWT signing is the right choice.
Detailed Explanation
RSA Keys for JWT Signing (RS256)
JSON Web Tokens (JWT) can be signed using RSA keys with the RS256 algorithm (RSA Signature with SHA-256). This enables asymmetric token verification where the signing authority and verifying parties use different keys.
RS256 vs HS256
| Feature | HS256 (HMAC) | RS256 (RSA) |
|---|---|---|
| Key type | Shared secret | Public/private key pair |
| Signing | Secret key | Private key |
| Verification | Same secret key | Public key |
| Key distribution | Must share secret securely | Only share public key |
| Use case | Single service | Microservices, third-party |
How RS256 Signing Works
JWT = Header.Payload.Signature
Header: {"alg": "RS256", "typ": "JWT"}
Payload: {"sub": "1234567890", "name": "John", "iat": 1516239022}
Signature = RSA_Sign(
SHA256(base64url(Header) + "." + base64url(Payload)),
privateKey
)
Implementation Example
// Signing (auth server — has private key)
const privateKey = await crypto.subtle.importKey(
"pkcs8", privateKeyDer,
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
false, ["sign"]
);
const signature = await crypto.subtle.sign(
"RSASSA-PKCS1-v1_5", privateKey, dataToSign
);
// Verification (any service — only needs public key)
const publicKey = await crypto.subtle.importKey(
"spki", publicKeyDer,
{ name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
false, ["verify"]
);
const isValid = await crypto.subtle.verify(
"RSASSA-PKCS1-v1_5", publicKey, signature, dataToSign
);
JWKS (JSON Web Key Set)
Public keys for JWT verification are often published as a JWKS endpoint:
{
"keys": [{
"kty": "RSA",
"kid": "key-id-1",
"use": "sig",
"n": "0vx7agoebGcQ...",
"e": "AQAB"
}]
}
Why RS256 for Microservices
In a microservices architecture, the authentication service signs tokens with its private key. All other services verify tokens using the public key — no shared secret distribution needed. Key rotation is simpler because only the JWKS endpoint needs updating.
Use Case
RS256 JWT signing is essential in microservices architectures, OAuth 2.0 / OpenID Connect implementations, and any system where multiple independent services need to verify tokens without sharing a secret. It is the standard approach used by Auth0, AWS Cognito, Google Identity, and other identity providers.