# JSON Web Encryption (JWE): Compact Tokens, alg, enc, and Key Rotation

> Learn how JWE compact tokens work: alg key management, enc content encryption, CEK and IV handling, kid rotation, header validation, and safe decryption failures.

**Quick answer:** A JWE hides and integrity-protects a payload in five dot-separated parts. alg selects how the content encryption key reaches the recipient, enc selects how the plaintext is encrypted. Use RSA-OAEP-256 or ECDH-ES with A256GCM, a fresh CEK and IV per message, header allowlists, and uniform decryption errors. JWE is not a signature, so pair it with JWS when sender identity matters.

## Key takeaways

- JWS signs a readable payload; JWE encrypts it. Confidentiality and sender authentication are separate properties, and neither one implies the other.
- A compact JWE has five parts: protected header, encrypted key, IV, ciphertext, and authentication tag. The protected header is authenticated as AAD and must still pass policy checks.
- alg is key management and enc is content encryption. RSA-OAEP-256 with A256GCM is a sound baseline; RSA1_5 is legacy and should be rejected.
- Generate a fresh CEK for every message, never reuse an IV with the same key, and verify the authentication tag before releasing any plaintext.
- Treat kid as a lookup hint, rotate keys with an overlap window, and return one uniform failure for every decryption error so padding and key oracles stay closed.

---

A compact JWE looks like a JWT with two extra segments and a stronger promise: the payload is unreadable and changes are detected. That promise is real but narrow. JWE protects confidentiality and ciphertext integrity, not sender identity, and it never replaces claim validation.

## JWS versus JWE: signing proves origin, encryption hides content

A JWS signs a readable payload. Its three segments are a base64url header, claims, and a signature; anyone can read the claims, and a verifier can test who signed them. A JWE encrypts the payload: the ciphertext is opaque, the tag detects modification, and only the decryption key holder recovers plaintext.

The structures answer different questions. "Who issued this and was it altered?" is a signature question. "Who may read this?" is an encryption question. Anyone with the recipient's RSA public key can create a JWE, so receiving one proves knowledge of that key, not the sender's identity.

| Property | JWS | JWE | Consequence |
| --- | --- | --- | --- |
| Payload | Readable | Ciphertext | PII belongs in a JWE |
| Integrity | Signature | AEAD tag | Both detect tampering at different layers |
| Sender | Proven by the verification key | Not proven by encryption | Add a JWS when origin matters |
| Key holder | Signer | Recipient | Encryption keys travel toward the reader |

Many systems need both. Sign-then-encrypt places a JWS inside a JWE and sets the outer `cty` to `JWT`; the recipient decrypts, verifies the inner signature, then validates claims. A [JWT decoder](/tools/jwt-decoder) expects three segments and cannot decrypt a five-part JWE.

## Compact serialization: the five parts of a JWE

Compact serialization is one string with five base64url segments separated by four dots. The first is the protected header: UTF-8 JSON carrying `alg`, `enc`, and usually `kid`, `typ`, or `cty`. It is protected because its encoded bytes are additional authenticated data; changing a header byte changes the AAD and makes the tag fail.

The second segment is the encrypted key: the RSA-OAEP-encrypted or wrapped CEK. For `dir` and direct ECDH-ES it is empty, producing two consecutive dots. That is valid and must match the expected `alg`. The third segment is the IV, the fourth the ciphertext, and the fifth the tag. The IV is public but unique per encryption; the tag binds the protected header as AAD to the IV and ciphertext and must be verified before any plaintext is used.

```text
eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6IjIwMjYtMTEifQ..SXZFeGFtcGxlMTJC.5n7Qm2Vk8pR1sT4uW9xY0aB3cD6eF2gH8jK1mN5pQ7rS9tU.RXhhbXBsZVRhZzE2Qnl0ZQ
```

Parse strictly. Reject anything other than five segments, padding outside base64url, duplicate header names, and oversized tokens. For `A256GCM` expect a 12-byte IV and a 16-byte tag; for `A128CBC-HS256` expect a 16-byte IV and tag.

## Key management with alg, content encryption with enc

`alg` names key management: how the CEK is encrypted, wrapped, agreed, or supplied. `enc` names content encryption: how the CEK encrypts plaintext and produces the tag. A token might pair `RSA-OAEP-256` with `A256GCM`, or `ECDH-ES+A256KW` with `A128CBC-HS256`. Both values come from a server-side allowlist, never a library's full catalog.

`enc` fixes the CEK length. A256GCM needs 32 bytes. A128CBC-HS256 also needs 32, split into a 16-byte HMAC key and a 16-byte AES key; the "128" describes the AES key, not the CEK. A256CBC-HS512 needs 64. `dir` requires a pre-shared key of exactly that size, and a wrong length must fail closed rather than be padded or truncated.

`zip` compresses before encryption, which can leak length side channels and expand small tokens enormously. Restrict it to controlled data, cap decompression, and reject unknown values. `crit` lists extensions the recipient must understand; unknown critical parameters are rejections.

## RSA-OAEP, ECDH-ES, A256GCM, and A128CBC-HS256 in practice

RSA-OAEP encrypts the CEK with the recipient's public key. It is simple and fits systems that already publish RSA keys. Use RSA-OAEP-256 with SHA-256 and at least 2048-bit keys. Anyone can encrypt to a public key, so it gives confidentiality, not sender authentication. RSA1_5 is legacy v1.5 padding whose errors are a decryption oracle; reject it.

ECDH-ES performs ephemeral-static Diffie-Hellman. The sender derives the CEK from an ephemeral private key and the recipient's public key, then publishes the ephemeral public key as `epk`; the encrypted key is empty. Validate the curve and point. ECDH-ES gives no forward secrecy against recipient key compromise, because `epk` travels in the header; anyone who later obtains the private key can recompute past CEKs. ECDH-ES+A256KW derives a key-encryption key and wraps a fresh CEK instead.

A256GCM is the usual choice: AEAD, 256-bit key, 96-bit IV, 128-bit tag. Its weakness is nonce discipline; reuse with the same key leaks plaintext relationships and can expose the authentication subkey. A128CBC-HS256 is AES-128-CBC plus HMAC-SHA-256 over AAD, IV, ciphertext, and length, truncated to 16 bytes. It needs a 128-bit IV and a 32-byte CEK split 16/16, and is safe only when the MAC is checked before decryption.

| Algorithm | Role | Key material | Main risk to control |
| --- | --- | --- | --- |
| RSA-OAEP-256 | Key management | Recipient RSA key, 2048 bits or more | No sender authentication; reject RSA1_5 |
| ECDH-ES | Direct agreement | EC key plus ephemeral key | Validate `epk`; no recipient forward secrecy |
| A256GCM | Content encryption | 32-byte CEK, 12-byte IV | Never reuse an IV with the same key |
| A128CBC-HS256 | Content encryption | 32-byte CEK split 16/16, 16-byte IV | Verify the MAC before decrypting |

The [AES-GCM tool](/tools/aes-gcm) shows authenticated encryption with a random IV but is not a JWE implementation. The [RSA key pair generator](/tools/rsa-keypair) makes RSA-OAEP test keys; production private keys belong in a KMS or HSM.

## CEK, IV, and authentication tag discipline

The CEK should be fresh per message, generated with a CSPRNG, never from a password, timestamp, or public hash. Wrapping modes generate and wrap it; ECDH-ES derives it; `dir` uses a pre-shared key. Direct mode is convenient but long-lived, so rotate it and separate senders from receivers.

IV uniqueness is mandatory. GCM with a repeated IV reveals XOR relationships and can allow forgery; use a random 96-bit IV within documented limits. CBC-HS needs a random 128-bit IV. Never derive an IV from a counter unless its state is durable across restarts and failovers.

The tag check is the boundary. Return plaintext only after constant-time tag verification; never decrypt first and compare afterward. The protected header is authenticated as AAD, but `alg`, `enc`, and `kid` remain attacker inputs that must pass policy before selecting a key. Do not log CEKs, plaintext, or full tokens.

## kid, key rotation, and protected header validation

`kid` selects a key from a set you trust; it is not an identity. Two issuers can reuse the same `kid`, so resolve within an issuer or tenant namespace. Never fetch `jku`, `x5u`, or an embedded `jwk` from the token unless that exact source is pinned; otherwise the token chooses its own decryption key.

Validate the header before using it. Accept only deployed `alg`/`enc` pairs, require `kid` when several keys are active, reject duplicate names and unknown `crit` values, and enforce `typ` and `cty` when your profile defines them. `cty: JWT` announces a nested token; ignoring it invites misparsing. Reject `zip` unless supported.

Rotation is a sequence. Publish the new key and `kid`, accept both, then encrypt with the new one. Keep the old private key until every token it can decrypt has expired plus skew, then remove it. Mark decrypt-only keys and monitor per-`kid` usage so a stuck client surfaces before retirement.

```ts
import { compactDecrypt, importJWK, type JWK } from "jose";

const expected = { alg: "RSA-OAEP-256", enc: "A256GCM" } as const;

export async function decryptJwe(token: string, keyring: Map<string, JWK>) {
  const { protectedHeader, plaintext } = await compactDecrypt(token, async (header) => {
    if (header.alg !== expected.alg || header.enc !== expected.enc) {
      throw new Error("unsupported algorithm");
    }
    if (!header.kid || !keyring.has(header.kid)) {
      throw new Error("unknown key");
    }
    return importJWK(keyring.get(header.kid)!, header.alg);
  });

  if (protectedHeader.alg !== expected.alg || protectedHeader.enc !== expected.enc) {
    throw new Error("unsupported algorithm");
  }
  return plaintext;
}
```

The resolver runs before decryption, so it must consult only server-side policy and the trusted keyring. The second check is defensive: the library has authenticated the header by then, but the allowlist decision still belongs to your code. Neither internal error string should reach the client verbatim.

## Why encryption alone is not authentication

Encryption answers "who may read this?", not "who wrote it?". Anyone with an RSA public key can encrypt; any holder of a shared key can produce a valid token; ECDH-ES only proves that someone encrypted to the recipient. The tag proves the ciphertext was made with the CEK, not who chose the plaintext.

Treating a decrypted token as an authenticated statement is an authorization bug. A JWE containing `{"sub":"admin"}` came from anyone who could encrypt to the service. Acting on `sub` without an issuer signature lets any holder of the public encryption key mint an admin token.

Compose instead. Sign the claims, encrypt the JWS, set `cty` to `JWT`, then decrypt, verify the inner signature, and validate `iss`, `aud`, `exp`, and `nbf`. Encryption also does not stop replay; short lifetimes, audience checks, and sender-constrained credentials such as DPoP or mTLS do.

## Decryption failures, error hygiene, and oracle resistance

Every decryption failure should look identical from outside: unknown `kid`, bad tag, malformed base64url, wrong key, and padding error all return the same status and body. Different errors create key-enumeration and padding oracles; the CBC padding oracle can decrypt without the key.

Order of operations matters. For CBC-HS, verify the MAC in constant time before decrypting and unpadding. For RSA1_5, decryption itself is the oracle, so reject it; if legacy forces it, follow RFC 7516's mitigation with a random CEK on failure and still return a generic error.

Cap token and decompressed size, rate-limit failures, and never fetch JWKS from an unknown `kid` without cache and circuit breaker. Do not log tokens, CEKs, or partial plaintext. Fail closed on key-service outages. After decrypt, parse strict JSON, validate the schema, check `exp` and `nbf`, enforce `iss` and `aud`, and treat plaintext as hostile.

## Verification checklist for a JWE implementation

Test negative cases as carefully as the happy path; self-decryption proves little. These checks are concrete enough for unit tests and a staging smoke test:

| Check | How to test | Pass criteria |
| --- | --- | --- |
| Header allowlist | Present `enc: A128CBC-HS256` or an unknown `alg` | Rejected before key selection; no plaintext |
| Key selection | Present an unknown `kid` and a token for another tenant | Same response as a bad tag; no header-driven fetch |
| Tamper detection | Flip one byte in header, IV, ciphertext, and tag | Every variant fails; no partial plaintext returned |
| IV uniqueness | Instrument encryption and encrypt many messages | Every IV is distinct; the CEK is fresh per message |
| Key rotation | Decrypt old and new `kid` tokens during overlap | Both succeed; a retired `kid` gets the generic error |
| Error hygiene | Compare unknown-key, bad-tag, and malformed-token responses | Identical status and body; no token or plaintext in logs |
| Claim validation | Decrypt an expired token and one with the wrong `aud` | Both rejected after decryption; no authorization decision |
| Legacy rejection | Submit an RSA1_5 token and an `alg: none` token | Both rejected; no fallback to another mode |

Run the suite against the production keyring and feature flags. A passing local test with a permissive allowlist says nothing about the deployed policy.

## Common mistakes and production rules

The expensive mistakes are predictable:

- Using JWE as a signature substitute and trusting decrypted claims as proof of origin.
- Reusing a CEK or IV across messages, especially with GCM.
- Trusting `alg`, `enc`, `kid`, `jku`, or `jwk` from the token instead of server-side policy.
- Returning different errors for unknown key, bad tag, and padding failure.
- Accepting RSA1_5 for compatibility and inheriting its padding-oracle history.
- Decrypting CBC ciphertext before verifying the MAC.
- Using `dir` with a human password or low-entropy key.
- Rotating no keys, then losing all retained tokens to one compromise.
- Skipping `iss`, `aud`, `exp`, and `nbf` because the payload was encrypted.
- Compressing attacker-controlled data without a size limit or side-channel review.

The production rules are short. Choose `alg` and `enc` from a small allowlist, prefer RSA-OAEP-256 or ECDH-ES+A256KW with A256GCM, and reject the rest. Generate a fresh CEK and unique IV per message, verify tags before releasing plaintext, and keep private keys in a KMS or HSM with a rotation schedule. Return one uniform decryption error, log only a correlation identifier and a redacted reason, and rate-limit failures. If the payload must prove who sent it, sign it first and encrypt the signed token. Encryption is a container, not a credential: signatures, audience checks, and key policy decide whether the content may be trusted.

## Frequently asked questions

### Is a JWE encrypted and signed at the same time?

No. A JWE provides confidentiality and integrity of the ciphertext under the selected algorithms, but it does not prove who created it. Anyone who holds the recipient's public key can encrypt to that recipient. When sender identity matters, put a JWS inside the JWE and verify both layers.

### Which alg and enc values should a new system use?

A practical baseline is RSA-OAEP-256 for key management with A256GCM for content encryption, or ECDH-ES+A256KW plus A256GCM when EC key management is available. Reject RSA1_5, unknown values, and any algorithm not on a small server-side allowlist.

### Can I reuse the same CEK or IV for several messages?

No. Generate a fresh CEK from a CSPRNG for each message and generate a new IV for every encryption under a given key. Reusing an IV with the same GCM key leaks plaintext relationships and can enable forgery; CBC modes also require unpredictable, unique IVs.

### Why is the encrypted key segment sometimes empty?

The empty segment is correct for direct key agreement such as ECDH-ES and for direct encryption with dir. In those modes no wrapped CEK travels in the token: the CEK is derived or pre-shared. Validate that emptiness against the expected alg instead of treating it as corruption.

### Why does a token that looks valid fail to decrypt?

Common causes are the wrong private key or kid, a key that was retired too early, a truncated or re-encoded token, or a header algorithm the server refuses. Log the reason internally, return a generic error externally, and compare the token's kid and alg with the active keyring.

## References

- [RFC 7516: JSON Web Encryption](https://www.rfc-editor.org/rfc/rfc7516)
- [RFC 7518: JSON Web Algorithms](https://www.rfc-editor.org/rfc/rfc7518)
- [RFC 8725: JWT Best Current Practices](https://www.rfc-editor.org/rfc/rfc8725)
- [OWASP: JSON Web Token Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_Cheat_Sheet.html)

---

- Canonical: https://www.jsonmind.com/guides/json-web-encryption
- Locale: en
- Published: 2026-11-17
- Updated: 2026-11-17
- Tools: jwt-decoder, aes-gcm, rsa-keypair