Powered by AppSignal & Oban Pro

JWS inside JWE in Livebook

livebooks/jose.livemd

JWS inside JWE in Livebook

This notebook signs a compact JWS (RFC 7515), encrypts it inside a compact JWE (RFC 7516), and verifies both layers before reading the payload. It then decrypts with an RSA-OAEP recipient key held behind a handle and shows the bounded errors. Keys are generated locally; no network access is needed beyond the Hex install.

Mix.install([{:request_seal, "~> 2.0"}])

Sign and verify a JWS

The payload is a sensor reading. {:jws, "EdDSA"} binds the handle to the JOSE algorithm name, which is separate from the HTTP signature name "ed25519".

reading = ~s({"sensor":"greenhouse-3","temperature_c":21})

{:ok, signing_handle} = RequestSeal.Custody.Local.generate({:jws, "EdDSA"}, [])
{:ok, signing_key} = RequestSeal.Custody.public_key(signing_handle)

{:ok, token} =
  RequestSeal.JOSE.JWS.sign([{"alg", "EdDSA"}, {"typ", "JOSE"}], reading, signing_handle)

jws_policy = %{
  algorithms: ["EdDSA"],
  timeout: 5_000,
  protected: %{expected: %{}, permitted: ~w(kid typ cty x5c), embedded_key: :refuse},
  key_resolver: fn %{algorithm: "EdDSA"} ->
    {:ok, %{algorithm: "EdDSA", key: signing_key}}
  end
}

{:ok, jws} = RequestSeal.JOSE.JWS.verify(token, jws_policy)
^reading = jws.payload
%{"alg" => "EdDSA", "typ" => "JOSE"} = jws.header
3 = length(String.split(token, "."))
IO.puts("JWS verified: #{byte_size(token)} compact bytes")

The resolver supplies the trusted key; a kid or x5c header alone confers no trust.

Reject a changed JWS

[protected, _payload, signature] = String.split(token, ".")
forged_payload = Base.url_encode64(~s({"sensor":"greenhouse-3","temperature_c":35}), padding: false)

{:error, %{reason: :invalid_signature, layer: :crypto}} =
  RequestSeal.JOSE.JWS.verify(Enum.join([protected, forged_payload, signature], "."), jws_policy)

# An algorithm outside the policy's allowlist rejects.
{:error, %{reason: :algorithm_not_permitted}} =
  RequestSeal.JOSE.JWS.verify(token, %{jws_policy | algorithms: ["ES256"]})

IO.puts("Changed payload and unlisted algorithm rejected")

Encrypt the signed token

The JWE wraps a fresh content-encryption key with an AES key you hold. The wrapping key stays in its sensitive custody holder.

{:ok, wrapping_handle} = RequestSeal.Custody.Local.generate({:jwe, "A256KW"}, [])

{:ok, encrypted} =
  RequestSeal.JOSE.JWE.encrypt(
    [{"alg", "A256KW"}, {"enc", "A256GCM"}, {"cty", "JWS"}],
    token,
    wrapping_handle
  )

5 = length(String.split(encrypted, "."))
IO.puts("JWE produced: #{byte_size(encrypted)} compact bytes")

Decrypt and verify both layers

RequestSeal.JOSE.Nested.verify/4 decrypts the JWE, checks its declared content type, then verifies the inner JWS. It returns both results only when every step succeeds.

jwe_policy = %{
  algorithms: ["A256KW"],
  encryption: ["A256GCM"],
  max_plaintext: 1_048_576,
  timeout: 5_000,
  resolve_timeout: 1000,
  unwrap_timeout: 1000,
  protected: %{expected: %{}, permitted: ~w(kid typ cty)},
  key_resolver: fn %{algorithm: "A256KW"} ->
    {:ok,
     %{
       algorithm: "A256KW",
       key: wrapping_handle
     }}
  end
}

{:ok, %{jwe: outer, jws: inner}} =
  RequestSeal.JOSE.Nested.verify(encrypted, jwe_policy, jws_policy, content_types: ["JWS"])

^token = outer.plaintext
^reading = inner.payload

# A ciphertext byte changed in transit fails authentication without releasing plaintext.
[h, k, iv, ciphertext, tag] = String.split(encrypted, ".")
<<first, rest::binary>> = Base.url_decode64!(ciphertext, padding: false)
flipped = Base.url_encode64(<<Bitwise.bxor(first, 1), rest::binary>>, padding: false)

{:error, %{reason: :decryption_failed, layer: :crypto}} =
  RequestSeal.JOSE.JWE.decrypt(Enum.join([h, k, iv, flipped, tag], "."), jwe_policy)

IO.puts("Nested envelope verified; altered ciphertext rejected")

Successful decryption shows the envelope was made with the shared wrapping key; it does not identify who made it. The inner signature identifies the signing key.

Decode an authenticated object and withhold malformed content

The strict object decoder narrows RFC 8259 with explicit byte and tree bounds, duplicate rejection, and integer-only numbers. content: :object decodes only after JWE authentication. A successful result carries both object and plaintext; decoding failure returns only an error.

{:ok, %{"sensor" => "greenhouse-3", "temperature_c" => 21}} =
  RequestSeal.JOSE.decode_object(inner.payload, max_bytes: 1024)

object_header = [{"alg", "A256KW"}, {"enc", "A256GCM"}, {"cty", "application/json"}]
object_policy = jwe_policy
  |> Map.put(:content, :object)
  |> Map.put(:protected, %{expected: %{"cty" => "application/json"}, permitted: []})
{:ok, object_token} = RequestSeal.JOSE.JWE.encrypt(object_header, reading, wrapping_handle)
{:ok, object_result} = RequestSeal.JOSE.JWE.decrypt(object_token, object_policy)
%{"temperature_c" => 21} = object_result.object
^reading = object_result.plaintext

{:ok, duplicate_token} = RequestSeal.JOSE.JWE.encrypt(
  object_header, ~s({"count":1,"count":2}), wrapping_handle
)
{:error, decode_error} = RequestSeal.JOSE.JWE.decrypt(duplicate_token, object_policy)
:duplicate_member = decode_error.reason
:input = decode_error.layer
false = Map.has_key?(decode_error, :plaintext)
false = Map.has_key?(decode_error, :object)
{:error, %{reason: :invalid_header}} =
  RequestSeal.JOSE.decode_object(~s({"temperature_c":21.4}), max_bytes: 1024)
IO.puts("Authenticated object decoded; duplicate members and floats rejected without a result")

Omitting content: or choosing :binary leaves object: nil. The byte budget for object content is max_plaintext; strings, nesting, container widths, and integer bounds also apply. See strict object content.

Decrypt with a recipient key handle

For RSA-OAEP, the recipient's private key lives in a handle bound to {:jwe, "RSA-OAEP-256"}. Senders encrypt to its public key; the resolver returns the handle.

{:ok, recipient} = RequestSeal.Custody.Local.generate(
  {:jwe, "RSA-OAEP-256"}, bits: 2048, timeout: 30_000
)
{:ok, recipient_public} = RequestSeal.Custody.public_key(recipient)

{:ok, sealed_note} =
  RequestSeal.JOSE.JWE.encrypt(
    [{"alg", "RSA-OAEP-256"}, {"enc", "A256GCM"}],
    "rotate the staging certificate on Friday",
    recipient_public
  )

recipient_policy = %{
  algorithms: ["RSA-OAEP-256"],
  encryption: ["A256GCM"],
  max_plaintext: 1_048_576,
  timeout: 5_000,
  resolve_timeout: 1000,
  unwrap_timeout: 1000,
  protected: %{expected: %{}, permitted: ~w(kid typ cty)},
  key_resolver: fn %{algorithm: "RSA-OAEP-256"} ->
    {:ok, %{algorithm: "RSA-OAEP-256", key: recipient}}
  end
}

{:ok, opened} = RequestSeal.JOSE.JWE.decrypt(sealed_note, recipient_policy)
"rotate the staging certificate on Friday" = opened.plaintext

# After release, decryption fails with the same error as a forged message.
:ok = RequestSeal.Custody.Local.release(recipient)
{:error, %{reason: :decryption_failed}} = RequestSeal.JOSE.JWE.decrypt(sealed_note, recipient_policy)

# The public-key health check tells the two cases apart.
{:error, %{reason: :key_not_found}} = RequestSeal.Custody.public_key(recipient)

:ok = RequestSeal.Custody.release(wrapping_handle)
:ok = RequestSeal.Custody.Local.release(signing_handle)
IO.puts("Recipient handle decrypted; released handle reported separately")

Next: the JOSE guide for options, bounds, and the full error list; key custody for supervised key owners.

ECDH-ES, ECDH-ES+A128KW, and ECDH-ES+A256KW also support public P-256, P-384, and X25519 recipients with unwrap-only custody handles, as defined by RFC 7518 §4.6 and RFC 8037. Each encryption uses a fresh ephemeral key; the protected header gains only its public epk.

JWE single and batch open share the guard and heir-notice lifecycle. With F = D + 100 ms and B(n) = 20 ms + 15 microseconds per item, caller wait-end is bounded by F + B(n), before cleanup and telemetry handlers. The policy excluding protected.expected is at most 4,096 words, including function environments; each expectation is at most 4,096 words and 16,384 binary bytes. Permitted UTF-8 names are at most 16,384 bytes each. Violations are :invalid_policy (positional for batch expectations). Resolvers with large keyrings capture an ETS table, registered name or persistent_term key. Returned handles have the same word and binary-byte bounds and oversized answers give :key_resolver_failed.