Skip to content

jam.jose

jose

JOSE tools.

Modules:

Name Description
jwe
jwk
jws
jwt
lists

Module for managing JWT black and white lists.

utils

Classes:

Name Description
JWE

JWE (JSON Web Encryption) implementation - RFC 7516.

JWK

JSON Web Key - RFC 7517.

JWKEC

Elliptic Curve Key - RFC 7517 Section 6.2.

JWKOct

Symmetric (Octet Sequence) Key - RFC 7517 Section 6.4.

JWKRSA

RSA Key - RFC 7517 Section 6.3.

JWKSet

JWK Set - RFC 7517 Section 5.

JWS

JWS (JSON Web Signature) implementation - RFC 7515.

JWT

JWT (JSON Web Token) implementation - RFC 7519.

Functions:

Name Description
create_jwe_instance

Create JWE instance.

create_jws_instance

Create JWS instance.

create_jwt_instance

Create JWT instance.

JWE

JWE(
    alg: str,
    enc: str,
    key: KeyLike | JWK,
    password: bytes | None = None,
    serializer: BaseEncoder
    | type[BaseEncoder] = JsonEncoder,
    logger: BaseLogger = logger,
)

Bases: BaseJWE

JWE (JSON Web Encryption) implementation - RFC 7516.

Provides encryption and decryption of data using JWK keys.

Example
>>> jwk = JWK.from_dict({"kty": "oct", "k": "your-secret-key"})
>>> jwe = JWE(alg="A128KW", enc="A128CBC-HS256", key=jwk)
>>> token = jwe.encrypt("secret data")
>>> plaintext = jwe.decrypt(token)

Parameters:

Name Type Description Default
alg str

Key management algorithm (e.g., "A128KW", "RSA-OAEP").

required
enc str

Content encryption algorithm (e.g., "A128CBC-HS256", "A256GCM").

required
key KeyLike | JWK

Key for encryption/decryption. Can be KeyLike or JWK.

required
password bytes | None

Password for encrypted private keys.

None
serializer BaseEncoder | type[BaseEncoder]

Encoder for serializing/deserializing JSON data.

JsonEncoder
logger BaseLogger

Logger instance.

logger

Methods:

Name Description
decrypt

Decrypt JWE token.

encrypt

Encrypt plaintext.

decrypt

decrypt(token: str) -> bytes

Decrypt JWE token.

Parameters:

Name Type Description Default
token str

JWE compact serialization string.

required

Returns:

Type Description
bytes

Decrypted plaintext bytes.

Raises:

Type Description
JamJWEDecryptionError

If decryption fails.

encrypt

encrypt(
    plaintext: bytes | str | dict[str, Any],
    header: dict[str, Any] | None = None,
) -> str

Encrypt plaintext.

Parameters:

Name Type Description Default
plaintext bytes | str | dict[str, Any]

Data to encrypt. If str, will be encoded to UTF-8. If dict, will be serialized using self._serializer.

required
header dict[str, Any] | None

Additional JWE header.

None

Returns:

Type Description
str

JWE compact serialization string.

Raises:

Type Description
JamJWEEncryptionError

If encryption fails.

JWK

JWK(data: dict[str, Any])

Bases: BaseJWK

JSON Web Key - RFC 7517.

Provides JWK validation and signing capabilities.

Example
>>> jwk = JWK.from_dict({"kty": "oct", "k": "your-secret-key"})
>>> jwk.sign(b"data", "HS256")
>>> jwk.verify(token)

Parameters:

Name Type Description Default
data dict[str, Any]

Validated JWK dict.

required

Methods:

Name Description
from_dict

Create JWK from dict.

sign

Sign data using JWK.

to_dict

Convert JWK to dict.

validate

Validate and normalize JWK dict.

verify

Verify JWS token and return payload.

Attributes:

Name Type Description
alg str | None

Get algorithm from JWK if set.

kid str | None

Get key ID if set.

kty str

Get key type.

alg property

alg: str | None

Get algorithm from JWK if set.

Returns:

Type Description
str | None

Algorithm or None.

kid property

kid: str | None

Get key ID if set.

Returns:

Type Description
str | None

Key ID or None.

kty property

kty: str

Get key type.

Returns:

Type Description
str

Key type (RSA, EC, oct).

from_dict classmethod

from_dict(data: dict[str, Any]) -> JWK

Create JWK from dict.

Alias for JWK.validate().

Parameters:

Name Type Description Default
data dict[str, Any]

JWK dict.

required

Returns:

Type Description
JWK

JWK instance.

sign

sign(data: bytes, alg: str | None = None) -> str

Sign data using JWK.

Parameters:

Name Type Description Default
data bytes

Data to sign.

required
alg str | None

Algorithm to use. If None, uses default for kty.

None

Returns:

Type Description
str

JWS compact serialization string.

Raises:

Type Description
ValueError

If algorithm is not supported or key is invalid.

to_dict

to_dict() -> dict[str, Any]

Convert JWK to dict.

Returns:

Type Description
dict[str, Any]

JWK dict.

validate staticmethod

validate(data: dict[str, Any]) -> JWK

Validate and normalize JWK dict.

Parameters:

Name Type Description Default
data dict[str, Any]

JWK dict to validate.

required

Returns:

Type Description
JWK

JWK instance.

Raises:

Type Description
JamJWKValidationError

If JWK is invalid.

verify

verify(
    token: str, alg: str | None = None
) -> dict[str, Any]

Verify JWS token and return payload.

Parameters:

Name Type Description Default
token str

JWS compact serialization token.

required
alg str | None

Algorithm to use. If None, uses default for kty.

None

Returns:

Type Description
dict[str, Any]

dict with 'header' and 'payload' keys.

Raises:

Type Description
ValueError

If signature is invalid.

JWKEC

Bases: JWKCommon

Elliptic Curve Key - RFC 7517 Section 6.2.

Represents an elliptic curve public or private key.

Example

ec_key: JWKEC = { ... "kty": "EC", ... "crv": "P-256", ... "x": "f83OJ3D2xF1Bg8v...", ... "y": "x_FEzRu9m36HLN_t...", ... }

Attributes:

Name Type Description
crv Literal['P-256', 'P-384', 'P-521']

Elliptic curve name. The curve on which the key is based.

d str

EC private key value. The private key value. Present only in private keys.

kty Literal['EC']

Key Type. Fixed to "EC".

x str

EC x coordinate. The x coordinate of the elliptic curve point.

y str

EC y coordinate. The y coordinate of the elliptic curve point.

crv instance-attribute

crv: Literal['P-256', 'P-384', 'P-521']

Elliptic curve name. The curve on which the key is based.

d instance-attribute

d: str

EC private key value. The private key value. Present only in private keys.

kty instance-attribute

kty: Literal['EC']

Key Type. Fixed to "EC".

x instance-attribute

x: str

EC x coordinate. The x coordinate of the elliptic curve point.

y instance-attribute

y: str

EC y coordinate. The y coordinate of the elliptic curve point.

JWKOct

Bases: JWKCommon

Symmetric (Octet Sequence) Key - RFC 7517 Section 6.4.

Represents a symmetric (secret) key.

Example

oct_key: JWKOct = { ... "kty": "oct", ... "k": "AyM32w-xOvmxxkBq...", ... }

Attributes:

Name Type Description
k str

Key value. The base64url-encoded symmetric key value.

kty Literal['oct']

Key Type. Fixed to "oct".

k instance-attribute

k: str

Key value. The base64url-encoded symmetric key value.

kty instance-attribute

kty: Literal['oct']

Key Type. Fixed to "oct".

JWKRSA

Bases: JWKCommon

RSA Key - RFC 7517 Section 6.3.

Represents an RSA public or private key.

Example

rsa_key: JWKRSA = { ... "kty": "RSA", ... "n": "0vx7agoebGcQSuu...", ... "e": "AQAB", ... }

Attributes:

Name Type Description
d str

RSA private exponent d. Present only in private keys.

dp str

First factor exponent. d mod (p-1). Present only in private keys.

dq str

Second factor exponent. d mod (q-1). Present only in private keys.

e str

RSA exponent e. The exponent value for the RSA public key.

kty Literal['RSA']

Key Type. Fixed to "RSA".

n str

RSA modulus n. The modulus value for the RSA public key.

p str

First prime p. First prime factor of n. Present only in private keys.

q str

Second prime q. Second prime factor of n. Present only in private keys.

qi str

First CRT coefficient. q^(-1) mod p. Present only in private keys.

d instance-attribute

d: str

RSA private exponent d. Present only in private keys.

dp instance-attribute

dp: str

First factor exponent. d mod (p-1). Present only in private keys.

dq instance-attribute

dq: str

Second factor exponent. d mod (q-1). Present only in private keys.

e instance-attribute

e: str

RSA exponent e. The exponent value for the RSA public key.

kty instance-attribute

kty: Literal['RSA']

Key Type. Fixed to "RSA".

n instance-attribute

n: str

RSA modulus n. The modulus value for the RSA public key.

p instance-attribute

p: str

First prime p. First prime factor of n. Present only in private keys.

q instance-attribute

q: str

Second prime q. Second prime factor of n. Present only in private keys.

qi instance-attribute

qi: str

First CRT coefficient. q^(-1) mod p. Present only in private keys.

JWKSet

JWKSet(keys: list[dict[str, Any]] | None = None)

Bases: BaseJWKSet

JWK Set - RFC 7517 Section 5.

Represents a set of JWKs. Used to organize and filter collections of keys.

Example
>>> jwkset = JWKSet(keys=[rsa_key, ec_key])
>>> jwkset.get_by_kid("my-key-id")
>>> jwkset.filter(kty="RSA")

Parameters:

Name Type Description Default
keys list[dict[str, Any]] | None

List of JWK dicts.

None

Methods:

Name Description
filter

Filter JWKs by criteria.

from_dict

Create JWKSet from dict.

get_by_kid

Get JWK by key ID (kid).

get_by_kty

Get all JWKs by key type.

to_dict

Convert JWKSet to dict.

filter

filter(**criteria: Any) -> list[dict[str, Any]]

Filter JWKs by criteria.

Parameters:

Name Type Description Default
**criteria Any

Filter criteria (kty, use, alg, key_ops, kid).

{}

Returns:

Type Description
list[dict[str, Any]]

List of matching JWK dicts.

from_dict classmethod

from_dict(data: dict[str, Any]) -> JWKSet

Create JWKSet from dict.

Parameters:

Name Type Description Default
data dict[str, Any]

Dict with "keys" key.

required

Returns:

Type Description
JWKSet

JWKSet instance.

Raises:

Type Description
JamJWKValidationError

If data is invalid.

get_by_kid

get_by_kid(kid: str) -> dict[str, Any] | None

Get JWK by key ID (kid).

Parameters:

Name Type Description Default
kid str

Key ID to search for.

required

Returns:

Type Description
dict[str, Any] | None

JWK dict if found, None otherwise.

get_by_kty

get_by_kty(kty: str) -> list[dict[str, Any]]

Get all JWKs by key type.

Parameters:

Name Type Description Default
kty str

Key type (RSA, EC, oct).

required

Returns:

Type Description
list[dict[str, Any]]

List of matching JWK dicts.

to_dict

to_dict() -> dict[str, Any]

Convert JWKSet to dict.

Returns:

Type Description
dict[str, Any]

dict with "keys" key containing list of JWKs.

JWS

JWS(
    alg: str,
    key: KeyLike | JWK,
    password: bytes | None = None,
    logger: BaseLogger = logger,
)

Bases: BaseJWS

JWS (JSON Web Signature) implementation - RFC 7515.

Parameters:

Name Type Description Default
alg str

Algorithm name

required
key KeyLike | JWK

Key to use for signing/verifying

required
password bytes | None

Password for encrypted private keys

None
logger BaseLogger

Logger instance

logger

Methods:

Name Description
deserialize_compact

Parse JWS Compact Serialization.

serialize_compact

Create JWS Compact Serialization.

sign

Sign data and return JWS compact serialization.

verify

Verify and parse JWS token.

deserialize_compact

deserialize_compact(
    s: str, validate: bool = True
) -> dict[str, Any]

Parse JWS Compact Serialization.

Parameters:

Name Type Description Default
s str

JWS in compact serialization format.

required
validate bool

Whether to validate signature. Defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict[str, Any]: Parsed JWS with keys: - header: Protected header dict - payload: Decoded payload bytes - signature: Raw signature bytes

Raises:

Type Description
JamJWSVerificationError

If validation fails or format is invalid.

serialize_compact

serialize_compact(
    protected: dict[str, Any], payload: bytes | str
) -> str

Create JWS Compact Serialization.

Parameters:

Name Type Description Default
protected dict[str, Any]

Protected header (must include 'alg').

required
payload bytes | str

Payload to sign. If dict, will be JSON encoded.

required

Returns:

Name Type Description
str str

JWS in compact serialization format: BASE64URL(protected).BASE64URL(payload).BASE64URL(signature)

sign

sign(
    header: dict[str, Any],
    data: bytes | str | dict[str, Any],
) -> str

Sign data and return JWS compact serialization.

Parameters:

Name Type Description Default
header dict[str, Any]

Protected header (alg will be added automatically).

required
data bytes | str | dict[str, Any]

Data to sign. If dict, will be JSON encoded.

required

Returns:

Type Description
str

JWS compact serialization string.

verify

verify(token: str, validate: bool = True) -> dict[str, Any]

Verify and parse JWS token.

Parameters:

Name Type Description Default
token str

JWS compact serialization string.

required
validate bool

Whether to validate signature.

True

Returns:

Type Description
dict[str, Any]

dict with 'header', 'payload', 'signature' keys.

JWT

JWT(
    alg: str | None = None,
    enc: str | None = None,
    secret_key: str | bytes | KeyLike | JWK | None = None,
    password: str | bytes | None = None,
    list: dict[str, Any] | None = None,
    serializer: BaseEncoder
    | type[BaseEncoder] = JsonEncoder,
    logger: BaseLogger = logger,
    jws: JWS | None = None,
    jwe: JWE | None = None,
)

Bases: BaseJWT

JWT (JSON Web Token) implementation - RFC 7519.

Supports JWS (signed), JWE (encrypted), and JWS+JWE (sign then encrypt) tokens.

Parameters:

Name Type Description Default
alg str | None

JWT algorithm name for signing (JWS). Used if jws is not provided.

None
enc str | None

JWE content encryption algorithm. If provided, creates encrypted JWT.

None
secret_key str | bytes | KeyLike | JWK | None

Key for signing/encryption.

None
password str | bytes | None

Password for encrypted private keys.

None
list dict[str, Any] | None

List config for token storage.

None
serializer BaseEncoder | type[BaseEncoder]

JSON encoder/decoder.

JsonEncoder
logger BaseLogger

Logger instance.

logger
jws JWS | None

Pre-built JWS instance. If provided, alg is ignored.

None
jwe JWE | None

Pre-built JWE instance. If provided, enc and secret_key are ignored.

None

Raises:

Type Description
ValueError

If neither alg/enc provided and no jws/jwe provided.

ValueError

If both alg and jws are provided.

ValueError

If both enc and jwe are provided.

JamJWTUnsupportedAlgorithm

If algorithm is not supported.

Methods:

Name Description
decode

Decode the JWT and return the header and payload.

decrypt

Decrypt JWE or JWS+JWE token.

encode

Encode the JWT with the given expire, header, and payload (JWS).

encrypt

Encrypt payload using JWE.

Attributes:

Name Type Description
jti str

The JWT ID.

jti property

jti: str

The JWT ID.

decode

decode(
    token: str, validate_claims: bool = True
) -> dict[str, Any]

Decode the JWT and return the header and payload.

Parameters:

Name Type Description Default
token str

JWT token.

required
validate_claims bool

Whether to validate exp/nbf claims. Defaults to True.

True

Returns:

Type Description
dict[str, Any]

dict with 'header' and 'payload' keys (both dicts).

Raises:

Type Description
JamConfigurationError

If alg is not provided.

JamJWSVerificationError

If token has invalid type.

JamJWTExpired

If token is expired.

JamJWTNotYetValid

If token is not yet valid.

decrypt

decrypt(token: str) -> dict[str, Any] | bytes

Decrypt JWE or JWS+JWE token.

If token is JWS+JWE (sign then encrypt): 1. Decrypt JWE to get JWS compact serialization 2. Verify JWS to get original payload

Parameters:

Name Type Description Default
token str

Encrypted JWT token.

required

Returns:

Type Description
dict[str, Any] | bytes

dict[str, Any]: Decrypted payload.

Raises:

Type Description
JamConfigurationError

If enc is not provided.

encode

encode(
    iss: str | None = None,
    sub: str | None = None,
    aud: str | None = None,
    exp: int | None = None,
    nbf: int | None = None,
    jti: str | None = None,
    header: dict[str, Any] | None = None,
    payload: dict[str, Any] | None = None,
) -> str

Encode the JWT with the given expire, header, and payload (JWS).

Parameters:

Name Type Description Default
exp int | None

The expiration time in seconds.

None
nbf int | None

The not-before time in seconds.

None
iss str | None

The issuer.

None
sub str | None

The subject.

None
aud str | None

The audience.

None
jti str | None

The JWT ID. If None, auto-generated.

None
header dict[str, Any] | None

The header to include in the JWT.

None
payload dict[str, Any] | None

The payload to include in the JWT.

None

Returns:

Name Type Description
str str

The encoded JWT (JWS compact serialization).

Raises:

Type Description
JamConfigurationError

If alg is not provided.

encrypt

encrypt(
    plaintext: bytes | str | dict[str, Any],
    header: dict[str, Any] | None = None,
) -> str

Encrypt payload using JWE.

If both jws and jwe are configured, creates JWS+JWE (sign then encrypt): 1. Create JWS compact serialization (sign) 2. Use JWS result as plaintext for JWE (encrypt)

Parameters:

Name Type Description Default
plaintext bytes | str | dict[str, Any]

Data to encrypt. If dict, will be JSON encoded.

required
header dict[str, Any] | None

Additional JWE header.

None

Returns:

Name Type Description
str str

Encrypted JWT (JWE or JWS+JWE).

Raises:

Type Description
JamConfigurationError

If jwe is not configured.

create_jwe_instance

create_jwe_instance(
    alg: str,
    enc: str,
    key: Any = None,
    password: bytes | None = None,
    serializer: BaseEncoder
    | type[BaseEncoder] = JsonEncoder,
    logger: BaseLogger = logger,
    **kwargs: Any,
) -> JWE

Create JWE instance.

create_jws_instance

create_jws_instance(
    alg: str,
    key: Any = None,
    password: bytes | None = None,
    logger: BaseLogger = logger,
    **kwargs: Any,
) -> JWS

Create JWS instance.

create_jwt_instance

create_jwt_instance(
    alg: str,
    secret: Any = None,
    secret_key: Any = None,
    password: str | bytes | None = None,
    list: dict[str, Any] | None = None,
    logger: BaseLogger = logger,
    serializer: BaseEncoder
    | type[BaseEncoder] = JsonEncoder,
    **kwargs: Any,
) -> JWT

Create JWT instance.