gose/jose/jwe_multi

JWE JSON Serialization for multi-recipient encryption and decryption (RFC 7516 Section 7.2.1).

Example

import gleam/json
import gose/algorithm
import gose/jose/jwe_multi
import gose/key

let k1 = key.generate_aes_kw_key(algorithm.Aes256)
let k2 = key.generate_aes_kw_key(algorithm.Aes128)
let plaintext = <<"hello":utf8>>

let message = jwe_multi.new(algorithm.AesGcm(algorithm.Aes256))
let assert Ok(message) =
  jwe_multi.add_recipient(
    message,
    algorithm.AesKeyWrap(algorithm.AesKw, algorithm.Aes256),
    key: k1,
  )
let assert Ok(message) =
  jwe_multi.add_recipient(
    message,
    algorithm.AesKeyWrap(algorithm.AesKw, algorithm.Aes128),
    key: k2,
  )
let assert Ok(encrypted) = jwe_multi.encrypt(message, plaintext:)

let json_str = jwe_multi.serialize_json(encrypted) |> json.to_string
let assert Ok(parsed) = jwe_multi.parse_json(json_str)
let assert Ok(dec) =
  jwe_multi.decryptor(
    algorithm.AesKeyWrap(algorithm.AesKw, algorithm.Aes256),
    algorithm.AesGcm(algorithm.Aes256),
    keys: [k1],
  )
let assert Ok(plaintext) = jwe_multi.decrypt(dec, parsed)

Rejected Algorithms

Direct and EcdhEs(EcdhEsDirect) are rejected because they derive the CEK directly rather than wrapping it, making multi-recipient impossible. Pbes2 is also excluded (requires a password, not a key).

Algorithm Pinning

Each decryptor is pinned to expected key encryption and content encryption algorithms. Mismatches are rejected.

Types

A decryptor pinned to expected algorithms and keys.

pub opaque type Decryptor

Phantom type for encrypted JWE.

pub type Encrypted

A multi-recipient JWE message parameterized by encryption state.

pub opaque type MultiJwe(state)

Phantom type for unencrypted JWE.

pub type Unencrypted

Values

pub fn add_recipient(
  message: MultiJwe(Unencrypted),
  alg: algorithm.KeyEncryptionAlg,
  key key: key.Key(String),
) -> Result(MultiJwe(Unencrypted), gose.GoseError)

Add a recipient with the given key encryption algorithm and key.

pub fn decrypt(
  decryptor: Decryptor,
  message: MultiJwe(Encrypted),
) -> Result(BitArray, gose.GoseError)

Decrypt a multi-recipient JWE.

pub fn decryptor(
  key_alg: algorithm.KeyEncryptionAlg,
  content_alg: algorithm.ContentAlg,
  keys keys: List(key.Key(String)),
) -> Result(Decryptor, gose.GoseError)

Build a decryptor pinned to expected algorithms and keys.

pub fn encrypt(
  message: MultiJwe(Unencrypted),
  plaintext plaintext: BitArray,
) -> Result(MultiJwe(Encrypted), gose.GoseError)

Encrypt the plaintext for all recipients.

pub fn new(enc: algorithm.ContentAlg) -> MultiJwe(Unencrypted)

Create a new multi-recipient JWE with the given content encryption algorithm.

pub fn parse_json(
  json_str: String,
) -> Result(MultiJwe(Encrypted), gose.GoseError)

Parse a JWE from JSON General Serialization format.

pub fn serialize_json(message: MultiJwe(Encrypted)) -> json.Json

Serialize as JWE JSON General Serialization.

Search Document