Signing-key rotation with kid & key rings
How to change a JWT or encryption key without logging everyone out. The kid header, active vs verification keys, and the same key-ring idea for AES-GCM secrets.
The concept
Keys must be rotated: when a key leaks, when an employee leaves, or on a schedule. With a single key, rotation invalidates every outstanding token, so everyone is logged out, and anything encrypted with the old key can no longer be decrypted.
A key ring holds several keys, each with an id:
- One active key signs or encrypts new data.
- All keys in the ring can verify or decrypt old data.
- Each token or ciphertext records which key was used, in the JWT
kidheader or a ciphertext prefix.
app.jwt:
active-key-id: v2
keys:
v1: ${APP_JWT_KEY_V1} # still accepted for verification
v2: ${APP_JWT_KEY_V2} # signs new tokens
// sign
Jwts.builder().header().keyId(props.activeKeyId()).and()
.subject(userId).signWith(props.activeKey()).compact();
// verify: choose the key from the token's kid
Jwts.parser().keyLocator(header -> props.resolveVerificationKey(((ProtectedHeader) header).getKeyId()))
.build().parseSignedClaims(token);
The rotation procedure
- Add
v2to the ring (it verifies only). - Deploy.
- Switch
active-key-idtov2. - Deploy. New tokens use v2, and old v1 tokens keep working.
- After the maximum token lifetime has passed, remove
v1.
For encrypted data, re-encrypt old rows in the background before you remove the old key.
In your projects
shared/security/JwtService.java · JwtSigningProperties.java.header().keyId(signingProperties.getActiveKeyId())
// ...
Jwts.parser().keyLocator(signingProperties::resolveVerificationKey)IR3D applies the same pattern to TotpSecretCipher (MFA secrets) and OAuthTokenCipher (social account tokens), both of which use rotatable AES-GCM key rings.
NimbusAccessTokens (D-20) · shared/crypto/KeyRingCipher.javaJWT keys come from APP_JWT_KEY_V1/V2 with a kid ring (decision D-20). KeyRingCipher (AES-256-GCM, APP_CRYPTO_KEY_V1) encrypts sensitive data at rest, including queued email bodies in the outbox.
Alternatives
| Approach | Notes |
|---|---|
| Key ring in config (yours) | Simple and effective for one service |
| JWKS endpoint with asymmetric keys | Standard for OIDC; verifiers fetch public keys by kid automatically |
| Cloud KMS (AWS KMS, GCP KMS) | Keys never leave the HSM; envelope encryption (KMS encrypts a data key, the data key encrypts the data); automatic rotation |
| HashiCorp Vault Transit | Encryption-as-a-service with versioned keys |
Related concepts you must know
- Envelope encryption: how KMS-backed systems encrypt large data cheaply.
- Crypto agility: designing so the algorithm can change too, by storing the algorithm and version with the ciphertext.
- Secret zero: something has to bootstrap access to the secrets, such as an IAM role (IR3D’s EC2 role reads SSM).