gose/jose/jwk

JSON Web Key (JWK) - RFC 7517

JSON serialization and deserialization for keys. Key creation, manipulation, and metadata are in gose.

Example

import gleam/json
import gose
import gose/jose/jwk
import kryptos/ec

// Generate an EC key and attach metadata
let k =
  gose.generate_ec(ec.P256)
  |> gose.with_kid("my-signing-key")

// Serialize to JSON
let json_string = jwk.to_json(k)
  |> json.to_string()

// Parse from a JSON string
let assert Ok(parsed) = jwk.from_json(json_string)
let assert Ok("my-signing-key") = gose.kid(parsed)

Duplicate Member Names

Per RFC 7517 Section 4, JWK member names must be unique. This implementation relies on gleam_json for parsing, which uses the first value when duplicate member names are present. Subsequent duplicates are ignored.

Unsupported Parameters

X.509 certificate chain parameters (RFC 7517 Section 4.6-4.9) are not supported:

JWKs containing any of these parameters are rejected with a ParseError during parsing. These parameters are not emitted during serialization.

Types

A key with a JWK-compatible string kid.

pub type Key =
  gose.Key(String)

Values

pub fn alg_from_string(
  s: String,
) -> Result(gose.Alg, gose.GoseError)

Parse an algorithm from its RFC string representation.

pub fn alg_to_string(alg: gose.Alg) -> String

Convert an algorithm (signing, key encryption, or content encryption) to its RFC string representation.

pub fn decoder() -> decode.Decoder(gose.Key(String))

Return a decoder for JWK values.

This lets you compose JWK decoding inside larger decode pipelines, for example with decode.field, decode.list, or json.parse.

Example

// Parse a key directly from a JSON string
let assert Ok(k) = json.parse(json_string, jwk.decoder())

// Use inside a larger decoder
use k <- decode.field("signing_key", jwk.decoder())
pub fn from_json(
  json_str: String,
) -> Result(gose.Key(String), gose.GoseError)

Parse a JWK from JSON.

pub fn from_json_bits(
  json_bits: BitArray,
) -> Result(gose.Key(String), gose.GoseError)

Parse a JWK from JSON provided as a BitArray.

pub fn thumbprint(
  key: gose.Key(kid),
  algorithm: hash.HashAlgorithm,
) -> Result(String, gose.GoseError)

Compute the JWK Thumbprint (RFC 7638).

The thumbprint is a base64url-encoded hash of the canonical JSON representation containing only the required public key members. Private keys produce the same thumbprint as their corresponding public keys.

RFC 7638 recommends SHA-256 as the hash, but allows other algorithms.

Example

let k = gose.generate_ec(ec.P256)
let assert Ok(thumbprint) = jwk.thumbprint(k, hash.Sha256)
pub fn to_json(k: gose.Key(String)) -> json.Json

Serialize a key to its JSON representation.

Search Document