API Reference

A Python implementation of CWT/COSE <https://python-cwt.readthedocs.io>

cwt.encode(claims: Claims | Dict[str, Any] | Dict[int, Any] | bytes, key: COSEKeyInterface, nonce: bytes = b'', recipients: List[RecipientInterface] = [], signers: List[Signer] = [], tagged: bool = False) bytes[source]
cwt.encode_and_mac(claims: Claims | Dict[int, Any] | bytes, key: COSEKeyInterface, recipients: List[RecipientInterface] = [], tagged: bool = False) bytes[source]
cwt.encode_and_sign(claims: Claims | Dict[int, Any] | bytes, key: COSEKeyInterface | None = None, signers: List[Signer] = [], tagged: bool = False) bytes[source]
cwt.encode_and_encrypt(claims: Claims | Dict[int, Any] | bytes, key: COSEKeyInterface, nonce: bytes = b'', recipients: List[RecipientInterface] = [], tagged: bool = False) bytes[source]
cwt.decode(data: bytes, keys: COSEKeyInterface | List[COSEKeyInterface], no_verify: bool = False) Dict[int, Any] | bytes[source]
cwt.set_private_claim_names(claim_names: Dict[str, int])[source]
class cwt.COSE(alg_auto_inclusion: bool = False, kid_auto_inclusion: bool = False, verify_kid: bool = False, ca_certs: str = '')[source]

Bases: CBORProcessor

A COSE (CBOR Object Signing and Encryption) Implementaion built on top of cbor2.

classmethod new(alg_auto_inclusion: bool = False, kid_auto_inclusion: bool = False, verify_kid: bool = False, ca_certs: str = '')[source]

Constructor.

Parameters:
  • alg_auto_inclusion (bool) – The indicator whether alg parameter is included in a proper header bucket automatically or not.

  • kid_auto_inclusion (bool) – The indicator whether kid parameter is included in a proper header bucket automatically or not.

  • verify_kid (bool) – The indicator whether kid verification is mandatory or not.

  • ca_certs (str) – The path to a file which contains a concatenated list of trusted root certificates. You should specify private CA certificates in your target system. There should be no need to use the public CA certificates for the Web PKI.

property alg_auto_inclusion: bool

If this property is True, an encode_and_*() function will automatically set the alg parameter in the header from the COSEKey argument.

property kid_auto_inclusion: bool

If this property is True, an encode_and_*() function will automatically set the kid parameter in the header from the COSEKey argument.

property verify_kid: bool

If this property is True, the decode() function will perform the verification and decoding process only if the kid of the COSE data to be decoded and one of the kid s in the key list given as an argument match exact.

encode(payload: bytes, key: COSEKeyInterface | None = None, protected: dict | None = None, unprotected: dict | None = None, recipients: List[RecipientInterface] = [], signers: List[Signer] = [], external_aad: bytes = b'', out: str = '') bytes[source]

Encodes COSE message with MAC, signing and encryption.

Parameters:
  • payload (bytes) – A content to be MACed, signed or encrypted.

  • key (Optional[COSEKeyInterface]) – A content encryption key as COSEKey.

  • protected (Optional[dict]) – Parameters that are to be cryptographically protected.

  • unprotected (Optional[dict]) – Parameters that are not cryptographically protected.

  • recipients (List[RecipientInterface]) – A list of recipient information structures.

  • signers (List[Signer]) – A list of signer information objects for multiple signer cases.

  • external_aad (bytes) – External additional authenticated data supplied by application.

  • out (str) –

    An output format. Only "cbor2/CBORTag" can be used. If "cbor2/CBORTag" is specified. This function will return encoded data as cbor2’s CBORTag object. If any other value is specified, it will return encoded data as bytes.

Returns:

A byte string of the encoded COSE or a

cbor2.CBORTag object.

Return type:

Union[bytes, CBORTag]

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode data.

encode_and_encrypt(payload: bytes, key: COSEKeyInterface | None = None, protected: dict | None = None, unprotected: dict | None = None, recipients: List[RecipientInterface] = [], external_aad: bytes = b'', out: str = '') bytes[source]

Encodes data with encryption.

Parameters:
  • payload (bytes) – A content to be encrypted.

  • key (Optional[COSEKeyInterface]) – A content encryption key as COSEKey.

  • protected (Optional[dict]) – Parameters that are to be cryptographically protected.

  • unprotected (Optional[dict]) – Parameters that are not cryptographically protected.

  • recipients (List[RecipientInterface]) – A list of recipient information structures.

  • external_aad (bytes) – External additional authenticated data supplied by application.

  • out (str) –

    An output format. Only "cbor2/CBORTag" can be used. If "cbor2/CBORTag" is specified. This function will return encoded data as cbor2’s CBORTag object. If any other value is specified, it will return encoded data as bytes.

Returns:

A byte string of the encoded COSE or a

cbor2.CBORTag object.

Return type:

Union[bytes, CBORTag]

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode data.

encode_and_mac(payload: bytes, key: COSEKeyInterface | None = None, protected: dict | None = None, unprotected: dict | None = None, recipients: List[RecipientInterface] = [], external_aad: bytes = b'', out: str = '') bytes | CBORTag[source]

Encodes data with MAC.

Parameters:
  • payload (bytes) – A content to be MACed.

  • key (COSEKeyInterface) – A COSE key as a MAC Authentication key.

  • protected (Optional[dict]) – Parameters that are to be cryptographically protected.

  • unprotected (Optional[dict]) – Parameters that are not cryptographically protected.

  • recipients (List[RecipientInterface]) – A list of recipient information structures.

  • external_aad (bytes) – External additional authenticated data supplied by application.

  • out (str) –

    An output format. Only "cbor2/CBORTag" can be used. If "cbor2/CBORTag" is specified. This function will return encoded data as cbor2’s CBORTag object. If any other value is specified, it will return encoded data as bytes.

Returns:

A byte string of the encoded COSE or a cbor2.CBORTag object.

Return type:

Union[bytes, CBORTag]

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode data.

encode_and_sign(payload: bytes, key: COSEKeyInterface | None = None, protected: dict | None = None, unprotected: dict | None = None, signers: List[Signer] = [], external_aad: bytes = b'', out: str = '') bytes | CBORTag[source]

Encodes data with signing.

Parameters:
  • payload (bytes) – A content to be signed.

  • key (Optional[COSEKeyInterface]) – A signing key for single signer cases. When the signers parameter is set, this key will be ignored and should not be set.

  • protected (Optional[dict]) – Parameters that are to be cryptographically protected.

  • unprotected (Optional[dict]) – Parameters that are not cryptographically protected.

  • signers (List[Signer]) – A list of signer information objects for multiple signer cases.

  • external_aad (bytes) – External additional authenticated data supplied by application.

  • out (str) –

    An output format. Only "cbor2/CBORTag" can be used. If "cbor2/CBORTag" is specified. This function will return encoded data as cbor2’s CBORTag object. If any other value is specified, it will return encoded data as bytes.

Returns:

A byte string of the encoded COSE or a

cbor2.CBORTag object.

Return type:

Union[bytes, CBORTag]

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode data.

decode(data: bytes | CBORTag, keys: COSEKeyInterface | List[COSEKeyInterface], context: List[Any] | Dict[str, Any] | None = None, external_aad: bytes = b'', detached_payload: bytes | None = None) bytes[source]

Verifies and decodes COSE data, and returns only payload.

Parameters:
  • data (Union[bytes, CBORTag]) – A byte string or cbor2.CBORTag of an encoded data.

  • keys (Union[COSEKeyInterface, List[COSEKeyInterface]]) – COSE key(s) to verify and decrypt the encoded data.

  • context (Optional[Union[Dict[str, Any], List[Any]]]) – A context information structure for key deriviation functions.

  • external_aad (bytes) – External additional authenticated data supplied by application.

  • detached_payload (Optional[bytes]) – The detached payload that should be verified with data.

Returns:

A byte string of decoded payload.

Return type:

bytes

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode data.

  • VerifyError – Failed to verify data.

decode_with_headers(data: bytes | CBORTag, keys: COSEKeyInterface | List[COSEKeyInterface], context: List[Any] | Dict[str, Any] | None = None, external_aad: bytes = b'', detached_payload: bytes | None = None) Tuple[Dict[int, Any], Dict[int, Any], bytes][source]

Verifies and decodes COSE data, and returns protected headers, unprotected headers and payload.

Parameters:
  • data (Union[bytes, CBORTag]) – A byte string or cbor2.CBORTag of an encoded data.

  • keys (Union[COSEKeyInterface, List[COSEKeyInterface]]) – COSE key(s) to verify and decrypt the encoded data.

  • context (Optional[Union[Dict[str, Any], List[Any]]]) – A context information structure for key deriviation functions.

  • external_aad (bytes) – External additional authenticated data supplied by application.

  • detached_payload (Optional[bytes]) – The detached payload that should be verified with data.

Returns:

A dictionary data of decoded protected headers, and a dictionary data of unprotected headers, and a byte string of decoded payload.

Return type:

Tuple[Dict[int, Any], Dict[int, Any], bytes]

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode data.

  • VerifyError – Failed to verify data.

class cwt.COSEAlgs(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

A128CTR = -65534
A192CTR = -65533
A256CTR = -65532
A128CBC = -65531
A192CBC = -65530
A256CBC = -65529
RS512 = -259
RS384 = -258
RS256 = -257
ES256K = -47
PS512 = -39
PS384 = -38
PS256 = -37
ES512 = -36
ES384 = -35
ECDH_SS_A256KW = -34
ECDH_SS_A192KW = -33
ECDH_SS_A128KW = -32
ECDH_ES_A256KW = -31
ECDH_ES_A192KW = -30
ECDH_ES_A128KW = -29
ECDH_SS_HKDF_512 = -28
ECDH_SS_HKDF_256 = -27
ECDH_ES_HKDF_512 = -26
ECDH_ES_HKDF_256 = -25
DIRECT_HKDF_SHA512 = -11
DIRECT_HKDF_SHA256 = -10
EDDSA = -8
ES256 = -7
DIRECT = -6
A256KW = -5
A192KW = -4
A128KW = -3
A128GCM = 1
A192GCM = 2
A256GCM = 3
HS256_64 = 4
HS256 = 5
HS384 = 6
HS512 = 7
AES_CCM_16_64_128 = 10
AES_CCM_16_64_256 = 11
AES_CCM_64_64_128 = 12
AES_CCM_64_64_256 = 13
CHACHA20_POLY1305 = 24
AES_CCM_16_128_128 = 30
AES_CCM_16_128_256 = 31
AES_CCM_64_128_128 = 32
AES_CCM_64_128_256 = 33
HPKE_BASE_P256_SHA256_AES128GCM = 35
HPKE_BASE_P256_SHA256_CHACHA20POLY1305 = 36
HPKE_BASE_P384_SHA384_AES256GCM = 37
HPKE_BASE_P384_SHA384_CHACHA20POLY1305 = 38
HPKE_BASE_P521_SHA512_AES256GCM = 39
HPKE_BASE_P521_SHA512_CHACHA20POLY1305 = 40
HPKE_BASE_X25519_SHA256_AES128GCM = 41
HPKE_BASE_X25519_SHA256_CHACHA20POLY1305 = 42
HPKE_BASE_X448_SHA512_AES256GCM = 43
HPKE_BASE_X448_SHA512_CHACHA20POLY1305 = 44
class cwt.COSEHeaders(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

ALG = 1
CRIT = 2
CTY = 3
KID = 4
IV = 5
PARTIAL_IV = 6
COUNTER_SIGNATURE = 7
COUNTER_SIGNATURE_0 = 9
KID_CONTEXT = 10
COUNTER_SIGNATURE_V2 = 11
COUNTER_SIGNATURE_0_V2 = 12
CWT_CLAIMS = 13
X5BAG = 32
X5CHAIN = 33
X5T = 34
X5U = 35
CUPH_NONCE = 256
CUPH_OWNER_PUB_KEY = 257
class cwt.COSEKeyCrvs(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

P256 = 1
P384 = 2
P521 = 3
X25519 = 4
X448 = 5
ED25519 = 6
ED448 = 7
SECP256K1 = 8
class cwt.COSEKeyOps(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

SIGN = 1
VERIFY = 2
ENCRYPT = 3
DECRYPT = 4
WRAP_KEY = 5
UNWRAP_KEY = 6
DERIVE_KEY = 7
DERIVE_BITS = 8
MAC_CREATE = 9
MAC_VERIFY = 10
class cwt.COSEKeyParams(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

KTY = 1
KID = 2
ALG = 3
KEY_OPS = 4
BASE_IV = 5
CRV = -1
X = -2
Y = -3
D = -4
RSA_N = -1
RSA_E = -2
RSA_D = -3
RSA_P = -4
RSA_Q = -5
RSA_DP = -6
RSA_DQ = -7
RSA_QINV = -8
RSA_OTHER = -9
RSA_R_I = -10
RsA_D_I = -11
RSA_T_I = -12
K = -1
class cwt.COSEKeyTypes(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

OKP = 1
EC2 = 2
RSA = 3
ASYMMETRIC = 4
class cwt.COSETypes(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

ENCRYPT0 = 1
ENCRYPT = 2
MAC0 = 3
MAC = 4
SIGN1 = 5
SIGN = 6
COUNTERSIGNATURE = 7
RECIPIENT = 8
SIGNATURE = 9
class cwt.COSEKey[source]

Bases: object

A COSEKeyInterface Builder.

static new(params: Dict[int, Any]) COSEKeyInterface[source]

Creates a COSE_Key object from a COSE_Key structure, which is a dictionary with numeric keys.

Parameters:

params (Dict[int, Any]) – A dictionary with numeric keys of a COSE key.

Returns:

A COSE key object.

Return type:

COSEKeyInterface

Raises:

ValueError – Invalid arguments.

classmethod generate_symmetric_key(alg: int | str = '', kid: bytes | str = b'', key_ops: List[int] | List[str] | None = None) COSEKeyInterface[source]

Generates a symmetric COSE key from from a randomly genarated byte string.

Parameters:
  • alg (Union[int, str]) – An algorithm label(int) or name(str). Supported alg are listed in Supported COSE Algorithms.

  • kid (Union[bytes, str]) – A key identifier.

  • key_ops (Union[List[int], List[str]]) – A list of key operation values. Following values can be used: 1("sign"), 2("verify"), 3("encrypt"), 4("decrypt"), 5("wrap key"), 6("unwrap key"), 7("derive key"), 8("derive bits"), 9("MAC create"), 10("MAC verify")

Returns:

A COSE key object.

Return type:

COSEKeyInterface

Raises:

ValueError – Invalid arguments.

classmethod from_symmetric_key(key: bytes | str = b'', alg: int | str = '', kid: bytes | str = b'', key_ops: List[int] | List[str] | None = None) COSEKeyInterface[source]

Creates a COSE key from a symmetric key.

Parameters:
  • key (Union[bytes, str]) – A key bytes or string.

  • alg (Union[int, str]) –

    An algorithm label(int) or name(str). Supported alg are listed in Supported COSE Algorithms.

  • kid (Union[bytes, str]) – A key identifier.

  • key_ops (Union[List[int], List[str]]) – A list of key operation values. Following values can be used: 1("sign"), 2("verify"), 3("encrypt"), 4("decrypt"), 5("wrap key"), 6("unwrap key"), 7("derive key"), 8("derive bits"), 9("MAC create"), 10("MAC verify")

Returns:

A COSE key object.

Return type:

COSEKeyInterface

Raises:

ValueError – Invalid arguments.

classmethod from_bytes(key_data: bytes) COSEKeyInterface[source]

Creates a COSE key from CBOR-formatted key data.

Parameters:

key_data (bytes) – CBOR-formatted key data.

Returns:

A COSE key object.

Return type:

COSEKeyInterface

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode the key data.

classmethod from_jwk(data: str | bytes | Dict[str, Any]) COSEKeyInterface[source]

Creates a COSE key from JWK (JSON Web Key).

Parameters:

jwk (Union[str, bytes, Dict[str, Any]]) – JWK-formatted key data.

Returns:

A COSE key object.

Return type:

COSEKeyInterface

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode the key data.

classmethod from_pem(key_data: str | bytes, alg: int | str = '', kid: bytes | str = b'', key_ops: List[int] | List[str] | None = None) COSEKeyInterface[source]

Creates a COSE key from PEM-formatted key data.

Parameters:
  • key_data (bytes) – A PEM-formatted key data.

  • alg (Union[int, str]) – An algorithm label(int) or name(str). Different from ::func::cwt.COSEKey.from_symmetric_key, it is only used when an algorithm cannot be specified by the PEM data, such as RSA family algorithms.

  • kid (Union[bytes, str]) – A key identifier.

  • key_ops (Union[List[int], List[str]]) – A list of key operation values. Following values can be used: 1("sign"), 2("verify"), 3("encrypt"), 4("decrypt"), 5("wrap key"), 6("unwrap key"), 7("derive key"), 8("derive bits"), 9("MAC create"), 10("MAC verify")

Returns:

A COSE key object.

Return type:

COSEKeyInterface

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode the key data.

class cwt.COSEMessage(type: COSETypes, msg: List[Any])[source]

Bases: CBORProcessor

The COSE message.

__init__(type: COSETypes, msg: List[Any])[source]

Constructor.

Parameters:
  • type (List[Any]) – A type of the COSE message.

  • msg (List[Any]) – A COSE message as a CBOR array.

classmethod loads(msg: bytes)[source]
classmethod from_cose_signature(signature: List[Any])[source]
classmethod from_cose_recipient(recipient: List[Any])[source]
property type: COSETypes

The identifier of the key type.

property protected: Dict[int, Any]

The protected headers as a CBOR object.

property unprotected: Dict[int, Any]

The unprotected headers as a CBOR object.

property payload: bytes

The payload of the COSE message.

property other_fields: List[bytes]

The list of other fields of the COSE message.

property signatures: List[List[Any]]

The list of signatures of the COSE message.

property recipients: List[List[Any]]

The list of recipients of the COSE message.

dumps() bytes[source]

Serializes the COSE message structure to a byte string.

countersign(signer: Signer, aad: bytes = b'', abbreviated: bool = False, tagged: bool = False, detached_payload: bytes | None = None) COSEMessage[source]

Countersigns to the COSE message with the signer specified.

Parameters:
  • signer (Signer) – A signer object that signs the COSE message.

  • aad (bytes) – The application supplied additional authenticated data.

  • abbreviated (bool) – The type of the countersignature (abbreviated or not).

  • tagged (bool) – The indicator whether the countersignature is tagged or not.

  • detached_payload (Optional[bytes]) – The detached payload that should be countersigned with the COSEMessage.

Returns:

The COSE message (self).

Return type:

COSEMessage

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to countersign.

counterverify(key: COSEKeyInterface, aad: bytes = b'', detached_payload: bytes | None = None) List[Any] | None[source]

Verifies a countersignature in the COSE message with the verification key specified.

Parameters:
  • key (COSEKeyInterface) – A COSEKey that is used to verify a signature in the COSE message.

  • aad (bytes) – The application supplied additional authenticated data.

  • detached_payload (Optional[bytes]) – The detached payload that should be counterverified with the COSEMessage.

Returns:

The COSE signature verified.

Return type:

Optional[List[Any]]

Raises:
  • ValueError – Invalid arguments.

  • VerifyError – Failed to verify.

detach_payload() Tuple[COSEMessage, bytes][source]

Detach a payload from the COSE message

Returns:

The COSE message (self), and a byte string of the detached payload.

Return type:

Tuple[COSEMessage, bytes]

Raises:

ValueError – The payload does not exist.

attach_payload(payload: bytes) COSEMessage[source]

Attach a detached content to the COSE message

Parameters:

payload (bytes) – A byte string of detached payload.

Returns:

The COSE message (self).

Return type:

COSEMessage

Raises:

ValueError – The payload already exist.

class cwt.CWT(expires_in: int = 3600, leeway: int = 60, ca_certs: str = '')[source]

Bases: CBORProcessor

A CWT (CBOR Web Token) Implementaion, which is built on top of COSE

cwt.cwt is a global object of this class initialized with default settings.

CBOR_TAG = 61
classmethod new(expires_in: int = 3600, leeway: int = 60, ca_certs: str = '')[source]

Constructor.

Parameters:
  • expires_in (int) – The default lifetime in seconds of CWT (default value: 3600).

  • leeway (int) – The default leeway in seconds for validating exp and nbf (default value: 60).

  • ca_certs (str) – The path to a file which contains a concatenated list of trusted root certificates. You should specify private CA certificates in your target system. There should be no need to use the public CA certificates for the Web PKI.

Examples

>>> from cwt import CWT, COSEKey
>>> ctx = CWT.new(expires_in=3600*24, leeway=10)
>>> key = COSEKey.from_symmetric_key(alg="HS256")
>>> token = ctx.encode(
...     {"iss": "coaps://as.example", "sub": "dajiaji", "cti": "123"},
...     key,
... )
>>> from cwt import CWT, COSEKey
>>> ctx = CWT.new(expires_in=3600*24, leeway=10, ca_certs="/path/to/ca_certs")
>>> key = COSEKey.from_pem(alg="ES256")
>>> token = ctx.encode(
...     {"iss": "coaps://as.example", "sub": "dajiaji", "cti": "123"},
...     key,
... )
property expires_in: int

The default lifetime in seconds of CWT. If exp is not found in claims, this value will be used with current time.

property leeway: int

The default leeway in seconds for validating exp and nbf.

property cose: COSE

The underlying COSE object.

encode(claims: Claims | Dict[str, Any] | Dict[int, Any] | bytes, key: COSEKeyInterface, nonce: bytes = b'', recipients: List[RecipientInterface] = [], signers: List[Signer] = [], tagged: bool = False) bytes[source]

Encodes CWT with MAC, signing or encryption. This is a wrapper function of the following functions for easy use:

Therefore, it must be clear whether the use of the specified key is for MAC, signing, or encryption. For this purpose, the key must have the key_ops parameter set to identify the usage.

Parameters:
  • claims (Union[Claims, Dict[str, Any], Dict[int, Any], bytes]) – A CWT claims object, or a JWT claims object, text string or byte string.

  • key (COSEKeyInterface) – A COSE key used to generate a MAC for the claims.

  • nonce (bytes) – A nonce for encryption.

  • recipients (List[RecipientInterface]) – A list of recipient information structures.

  • signers (List[Signer]) – A list of signer information structures for multiple signer cases.

  • tagged (bool) – An indicator whether the response is wrapped by CWT tag(61) or not.

Returns:

A byte string of the encoded CWT.

Return type:

bytes

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode the claims.

encode_and_mac(claims: Claims | Dict[int, Any] | bytes, key: COSEKeyInterface, recipients: List[RecipientInterface] = [], tagged: bool = False) bytes[source]

Encodes with MAC.

Parameters:
  • claims (Union[Claims, Dict[int, Any], bytes]) – A CWT claims object or byte string.

  • key (COSEKeyInterface) – A COSE key used to generate a MAC for the claims.

  • recipients (Optional[List[RecipientInterface]]) – A list of recipient information structures.

  • tagged (bool) – An indicator whether the response is wrapped by CWT tag(61) or not.

Returns:

A byte string of the encoded CWT.

Return type:

bytes

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode the claims.

encode_and_sign(claims: Claims | Dict[int, Any] | bytes, key: COSEKeyInterface | None = None, signers: List[Signer] = [], tagged: bool = False) bytes[source]

Encodes CWT with signing.

Parameters:
  • claims (Claims, Union[Dict[int, Any], bytes]) – A CWT claims object or byte string.

  • key (Optional[COSEKeyInterface]) – A COSE key or a list of the keys used to sign claims. When the signers parameter is set, this key parameter will be ignored and should not be set.

  • signers (List[Signer]) – A list of signer information structures for multiple signer cases.

  • tagged (bool) – An indicator whether the response is wrapped by CWT tag(61) or not.

Returns:

A byte string of the encoded CWT.

Return type:

bytes

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode the claims.

encode_and_encrypt(claims: Claims | Dict[int, Any] | bytes, key: COSEKeyInterface, nonce: bytes = b'', recipients: List[RecipientInterface] = [], tagged: bool = False) bytes[source]

Encodes CWT with encryption.

Parameters:
  • claims (Claims, Union[Dict[int, Any], bytes]) – A CWT claims object or byte string.

  • key (COSEKeyInterface) – A COSE key used to encrypt the claims.

  • nonce (bytes) – A nonce for encryption.

  • recipients (List[RecipientInterface]) – A list of recipient information structures.

  • tagged (bool) – An indicator whether the response is wrapped by CWT tag(61) or not.

Returns:

A byte string of the encoded CWT.

Return type:

bytes

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode the claims.

decode(data: bytes, keys: COSEKeyInterface | List[COSEKeyInterface], no_verify: bool = False) Dict[int, Any] | bytes[source]

Verifies and decodes CWT.

Parameters:
  • data (bytes) – A byte string of an encoded CWT.

  • keys (Union[COSEKeyInterface, List[COSEKeyInterface]]) – A COSE key or a list of the keys used to verify and decrypt the encoded CWT.

  • no_verify (bool) – An indicator whether token verification is skiped or not.

Returns:

A byte string of the decoded CWT.

Return type:

Union[Dict[int, Any], bytes]

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode the CWT.

  • VerifyError – Failed to verify the CWT.

set_private_claim_names(claim_names: Dict[str, int])[source]

Sets private claim definitions. The definitions will be used in encode when it is called with JSON-based claims.

Parameters:

claim_names (Dict[str, int]) – A set of private claim definitions which consist of a readable claim name(str) and a claim key(int). The claim key should be less than -65536 but you can use the numbers other than pre-registered numbers listed in IANA Registry.

Raises:

ValueError – Invalid arguments.

class cwt.CWTClaims(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: IntEnum

HCERT = -260
EUPH_NONCE = -259
EAT_MAROE_PREFIX = -258
EAT_FDO = -257
ISS = 1
SUB = 2
AUD = 3
EXP = 4
NBF = 5
IAT = 6
CTI = 7
CNF = 8
NONCE = 10
UEID = 11
OEMID = 13
SEC_LEVEL = 14
SEC_BOOT = 15
DBG_STAT = 16
LOCATION = 17
EAT_PROFILE = 18
SUBMODS = 20
class cwt.EncryptedCOSEKey[source]

Bases: CBORProcessor

An encrypted COSE key.

static from_cose_key(key: COSEKeyInterface, encryption_key: COSEKeyInterface, nonce: bytes = b'', tagged: bool = False) List[Any] | bytes[source]

Returns an encrypted COSE key formatted to COSE_Encrypt0 structure.

Parameters:
  • key – COSEKeyInterface: A key to be encrypted.

  • encryption_key – COSEKeyInterface: An encryption key to encrypt the target COSE key.

  • nonce (bytes) – A nonce for encryption.

  • tagged (bool) – An indicator whether the response is wrapped by CWT tag(61) or not.

Returns:

A COSE_Encrypt0 structure of the target COSE key.

Return type:

Union[List[Any], bytes]

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encrypt the COSE key.

static to_cose_key(key: List[Any], encryption_key: COSEKeyInterface) COSEKeyInterface[source]

Returns an decrypted COSE key.

Parameters:
  • key – COSEKeyInterface: A key formatted to COSE_Encrypt0 structure to be decrypted.

  • encryption_key – COSEKeyInterface: An encryption key to decrypt the target COSE key.

Returns:

A key decrypted.

Return type:

COSEKeyInterface

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode the COSE key.

  • VerifyError – Failed to verify the COSE key.

class cwt.Claims(claims: Dict[int, Any], claim_names: Dict[str, int] = {'EAT-FDO': -257, 'EATMAROEPrefix': -258, 'EUPHNonce': -259, 'aud': 3, 'cnf': 8, 'cti': 7, 'dbgstat': 16, 'eat_profile': 18, 'exp': 4, 'hcert': -260, 'iat': 6, 'iss': 1, 'location': 17, 'nbf': 5, 'nonce': 10, 'oemid': 13, 'secboot': 15, 'seclevel': 14, 'sub': 2, 'submods': 20, 'ueid': 11})[source]

Bases: object

A class for handling CWT Claims like JWT claims.

classmethod new(claims: Dict[int, Any], private_claim_names: Dict[str, int] = {})[source]

Creates a Claims object from a CBOR-like(Dict[int, Any]) claim object.

Parameters:
  • claims (Dict[str, Any]) – A CBOR-like(Dict[int, Any]) claim object.

  • private_claim_names (Dict[str, int]) –

    A set of private claim definitions which consist of a readable claim name(str) and a claim key(int). The claim key should be less than -65536 but you can use the numbers other than pre-registered numbers listed in IANA Registry.

Returns:

A CWT claims object.

Return type:

Claims

Raises:

ValueError – Invalid arguments.

classmethod from_json(claims: str | bytes | Dict[str, Any], private_claim_names: Dict[str, int] = {})[source]

Converts a JWT claims object into a CWT claims object which has numeric keys. If a key string in JSON data cannot be mapped to a numeric key, it will be skipped.

Parameters:
  • claims (Union[str, bytes, Dict[str, Any]]) – A JWT claims object to be converted.

  • private_claim_names (Dict[str, int]) –

    A set of private claim definitions which consist of a readable claim name(str) and a claim key(int). The claim key should be less than -65536 but you can use the numbers other than pre-registered numbers listed in IANA Registry.

Returns:

A CWT claims object.

Return type:

Claims

Raises:

ValueError – Invalid arguments.

classmethod validate(claims: Dict[int, Any])[source]

Validates a CWT claims object.

Parameters:

claims (Dict[int, Any]) – A CWT claims object to be validated.

Raises:

ValueError – Failed to verify.

property iss: str | None
property sub: str | None
property aud: str | None
property exp: int | None
property nbf: int | None
property iat: int | None
property cti: str | None
property hcert: dict | None
property cnf: Dict[int, Any] | List[Any] | str | None
get(key: str | int) Any[source]

Gets a claim value with a claim key.

Parameters:

key (Union[str, int]) – A claim key.

Returns:

The value of the claim.

Return type:

Any

to_dict() Dict[int, Any][source]

Returns a raw claim object.

Returns:

The value of the raw claim.

Return type:

Any

class cwt.Recipient[source]

Bases: object

A RecipientInterface Builder.

classmethod new(protected: dict = {}, unprotected: dict = {}, ciphertext: bytes = b'', recipients: List[Any] = [], sender_key: COSEKeyInterface | None = None, recipient_key: COSEKeyInterface | None = None, context: List[Any] | Dict[str, Any] | None = None) RecipientInterface[source]

Creates a recipient from a CBOR-like dictionary with numeric keys.

Parameters:
  • protected (dict) – Parameters that are to be cryptographically protected.

  • unprotected (dict) – Parameters that are not cryptographically protected.

  • ciphertext (List[Any]) – A cipher text.

  • sender_key (Optional[COSEKeyInterface]) – A sender private key as COSEKey.

  • recipient_key (Optional[COSEKeyInterface]) – A recipient public key as COSEKey.

  • context (Optional[Union[List[Any], Dict[str, Any]]]) – Context information structure.

Returns:

A recipient object.

Return type:

RecipientInterface

Raises:

ValueError – Invalid arguments.

classmethod from_list(recipient: List[Any], context: List[Any] | Dict[str, Any] | None = None) RecipientInterface[source]

Creates a recipient from a raw COSE array data.

Parameters:

data (Union[str, bytes, Dict[str, Any]]) – JSON-formatted recipient data.

Returns:

A recipient object.

Return type:

RecipientInterface

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode the key data.

class cwt.Signer(cose_key: COSEKeyInterface, protected: Dict[int, Any] | bytes, unprotected: Dict[int, Any], signature: bytes = b'')[source]

Bases: CBORProcessor

A Signer information.

property cose_key: COSEKeyInterface

The COSE key for the signer.

property protected: bytes

The parameters that are to be cryptographically protected.

property unprotected: Dict[int, Any]

The parameters that are not cryptographically protected.

property signature: bytes

The signature that the signer signed.

classmethod new(cose_key: COSEKeyInterface, protected: dict | bytes = {}, unprotected: dict = {}, signature: bytes = b'')[source]

Creates a signer information object (COSE_Signature).

Parameters:
  • cose_key (COSEKey) – A signature key for the signer.

  • protected (Union[dict, bytes]) – Parameters that are to be cryptographically protected.

  • unprotected (dict) – Parameters that are not cryptographically protected.

  • signature (bytes) – A signature as bytes.

Returns:

A signer information object.

Return type:

Signer

Raises:

ValueError – Invalid arguments.

classmethod from_jwk(data: str | bytes | Dict[str, Any])[source]

Creates a signer information object (COSE_Signature) from JWK. The alg in the JWK will be included in the protected header, and the kid in the JWT will be include in the unprotected header. If you want to include any other parameters in the protected/unprotected header, you have to use Signer.new.

Parameters:

data (Union[str, bytes, Dict[str, Any]]) – A JWK.

Returns:

A signer information object.

Return type:

Signer

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode the key data.

classmethod from_pem(data: str | bytes, alg: int | str = '', kid: bytes | str = b'')[source]

Creates a signer information object (COSE_Signature) from PEM-formatted key. The alg in the JWK will be included in the protected header, and the kid in the JWT will be include in the unprotected header. If you want to include any other parameters in the protected/unprotected header, you have to use Signer.new.

Parameters:
  • data (Union[str, bytes]) – A PEM-formatted key.

  • alg (Union[int, str]) – An algorithm label(int) or name(str). It is only used when an algorithm cannot be specified by the PEM data, such as RSA family algorithms.

  • kid (Union[bytes, str]) – A key identifier.

Returns:

A signer information object.

Return type:

Signer

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode the key data.

sign(msg: bytes)[source]

Returns a digital signature for the specified message using the specified key value.

Parameters:

msg (bytes) – A message to be signed.

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to sign the message.

verify(msg: bytes)[source]

Verifies that the specified digital signature is valid for the specified message.

Parameters:

msg (bytes) – A message to be verified.

Raises:
  • ValueError – Invalid arguments.

  • VerifyError – Failed to verify.

cwt.load_pem_hcert_dsc(cert: str | bytes) COSEKeyInterface[source]

Loads PEM-formatted DSC (Digital Signing Certificate) issued by CSCA (Certificate Signing Certificate Authority) as a COSEKey. At this time, the kid of the COSE key will be generated as a 8-byte truncated SHA256 fingerprint of the DSC complient with Electronic Health Certificate Specification.

Parameters:

cert (str) – A DSC.

Returns:

A DSC’s public key as a COSE key.

Return type:

COSEKeyInterface

exception cwt.CWTError[source]

Bases: Exception

Base class for all exceptions.

exception cwt.EncodeError[source]

Bases: CWTError

An Exception occurred when a CWT/COSE encoding process failed.

exception cwt.DecodeError[source]

Bases: CWTError

An Exception occurred when a CWT/COSE decoding process failed.

exception cwt.VerifyError[source]

Bases: CWTError

An Exception occurred when a verification process failed.

class cwt.cose_key_interface.COSEKeyInterface(params: Dict[int, Any])[source]

Bases: CBORProcessor

The interface class for a COSE Key used for MAC, signing/verifying and encryption/decryption.

__init__(params: Dict[int, Any])[source]

Constructor.

Parameters:

params (Dict[int, Any]) – A COSE key common parameter object formatted to CBOR-like structure ((Dict[int, Any])).

property kty: int

The identifier of the key type.

property kid: bytes | None

The key identifier.

property alg: int | None

The algorithm that is used with the key.

property key_ops: List[int]

A set of permissible operations that the key is to be used for.

property base_iv: bytes | None

Base IV to be xor-ed with Partial IVs.

property key: Any

The body of the key. It can be bytes or various PublicKey/PrivateKey objects defined in pyca/cryptography

property crv: int

The curve (crv parameter value) of the key.

to_bytes() bytes[source]

Serializes the body of the key as a byte string.

to_dict() Dict[int, Any][source]

Returns the CBOR-like structure (Dict[int, Any]) of the COSE key.

Returns:

The CBOR-like structure of the COSE key.

Return type:

Dict[int, Any]

generate_nonce() bytes[source]

Returns a nonce with the size suitable for the algorithm. This function will be called internally in CWT when no nonce is specified by the application. This function adopts secrets.token_bytes() to generate a nonce. If you do not want to use it, you should explicitly set a nonce to CWT functions (e.g., encode_and_encrypt).

Returns:

A byte string of the generated nonce.

Return type:

bytes

Raises:

NotImplementedError – Not implemented.

sign(msg: bytes) bytes[source]

Returns a digital signature for the specified message using the specified key value.

Parameters:

msg (bytes) – A message to be signed.

Returns:

The byte string of the encoded CWT.

Return type:

bytes

Raises:
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • EncodeError – Failed to sign the message.

verify(msg: bytes, sig: bytes)[source]

Verifies that the specified digital signature is valid for the specified message.

Parameters:
  • msg (bytes) – A message to be verified.

  • sig (bytes) – A digital signature of the message.

Returns:

The byte string of the encoded CWT.

Return type:

bytes

Raises:
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • VerifyError – Failed to verify.

validate_certificate(ca_certs: List[bytes]) bool[source]

Validate a certificate bound to the key with given trusted CA certificates if the key has x5c parameter.

Parameters:

ca_certs (List[bytes]) – A list of DER-formatted trusted root CA certificates which contains a concatenated list of trusted root certificates. You should specify private CA certificates in your target system. There should be no need to use the public CA certificates for the Web PKI.

Returns:

The indicator whether the validation is done or not.

Return type:

bool

Raises:
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • VerifyError – Failed to verify.

encrypt(msg: bytes, nonce: bytes, aad: bytes) bytes[source]

Encrypts the specified message.

Parameters:
  • msg (bytes) – A message to be encrypted.

  • nonce (bytes) – A nonce for encryption.

  • aad (bytes) – Additional authenticated data.

Returns:

The byte string of encrypted data.

Return type:

bytes

Raises:
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • EncodeError – Failed to encrypt the message.

decrypt(msg: bytes, nonce: bytes, aad: bytes) bytes[source]

Decrypts the specified message.

Parameters:
  • msg (bytes) – An encrypted message.

  • nonce (bytes) – A nonce for encryption.

  • aad (bytes) – Additional authenticated data.

Returns:

The byte string of the decrypted data.

Return type:

bytes

Raises:
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • DecodeError – Failed to decrypt the message.

wrap_key(key_to_wrap: bytes) bytes[source]

Wraps a key.

Parameters:

key_to_wrap – A key to wrap.

Returns:

A wrapped key as bytes.

Return type:

bytes

Raises:
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • EncodeError – Failed to derive key.

unwrap_key(wrapped_key: bytes) bytes[source]

Unwraps a key.

Parameters:

wrapped_key – A key to be unwrapped.

Returns:

An unwrapped key as bytes.

Return type:

bytes

Raises:
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • DecodeError – Failed to unwrap key.

derive_bytes(length: int, material: bytes = b'', info: bytes = b'', public_key: Any | None = None) bytes[source]

Derives a byte string with a key material or key exchange.

Parameters:
  • length (int) – The length of derived byte string.

  • material (bytes) – A key material as bytes.

  • info (bytes) – application supplied information.

  • public_key – A public key for key derivation with key exchange.

Returns:

A derived byte string.

Return type:

bytes

Raises:
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • EncodeError – Failed to derive key.

class cwt.recipient_interface.RecipientInterface(protected: Dict[int, Any] | None = None, unprotected: Dict[int, Any] | None = None, ciphertext: bytes = b'', recipients: List[Any] = [], key_ops: List[int] = [], key: bytes = b'')[source]

Bases: CBORProcessor

The interface class for a COSE Recipient.

__init__(protected: Dict[int, Any] | None = None, unprotected: Dict[int, Any] | None = None, ciphertext: bytes = b'', recipients: List[Any] = [], key_ops: List[int] = [], key: bytes = b'')[source]

Constructor.

Parameters:
  • protected (Optional[Dict[int, Any]]) – Parameters that are to be cryptographically protected.

  • unprotected (Optional[Dict[int, Any]]) – Parameters that are not cryptographically protected.

  • ciphertext – A ciphertext encoded as bytes.

  • recipients – A list of recipient information structures.

  • key_ops – A list of operations that the key is to be used for.

  • key – A body of the key as bytes.

property kid: bytes

The key identifier.

property alg: int

The algorithm that is used with the key.

property protected: Dict[int, Any]

The parameters that are to be cryptographically protected.

property b_protected: bytes

The binary encoded protected header.

property unprotected: Dict[int, Any]

The parameters that are not cryptographically protected.

property ciphertext: bytes

The ciphertext encoded as bytes

property recipients: List[Any]

The list of recipient information structures.

property context: List[Any]

The recipient context information.

to_list() List[Any][source]

Returns the recipient information as a COSE recipient structure.

Returns:

The recipient structure.

Return type:

List[Any]

encode(plaintext: bytes = b'', aad: bytes = b'') Tuple[List[Any], COSEKeyInterface | None][source]

Encrypts a specified plaintext to the ciphertext in the COSE_Recipient structure with the recipient-specific method (e.g., key wrapping, key agreement, or the combination of them) and sets up the related information (context information or ciphertext) in the recipient structure.

This function will be called in COSE.encode_* functions so applications do not need to call it directly.

Parameters:
  • plaintext (bytes) – A plaing text to be encrypted. In most of the cases, the plaintext is a byte string of a content encryption key.

  • external_aad (bytes) – External additional authenticated data for AEAD.

  • aad_context (bytes) – An additional authenticated data context to build an Enc_structure internally.

Returns:

The encoded COSE_Recipient structure

and a derived key.

Return type:

Tuple[List[Any], Optional[COSEKeyInterface]]

Raises:
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode(e.g., wrap, derive) the key.

decode(key: COSEKeyInterface, aad: bytes = b'', alg: int = 0, as_cose_key: bool = False) bytes | COSEKeyInterface[source]

Decrypts the ciphertext in the COSE_Recipient structure with the recipient-specific method (e.g., key wrapping, key agreement, or the combination of them).

This function will be called in COSE.decode so applications do not need to call it directly.

Parameters:
  • key (COSEKeyInterface) – The external key to be used for decrypting the ciphertext in the COSE_Recipient structure.

  • external_aad (bytes) – External additional authenticated data for AEAD.

  • aad_context (bytes) – An additional authenticated data context to build an Enc_structure internally.

  • alg (int) – The algorithm of the key derived.

  • as_cose_key (bool) – The indicator whether the output will be returned as a COSEKey or not.

Returns:

The decrypted ciphertext field or The COSEKey

converted from the decrypted ciphertext.

Return type:

Union[bytes, COSEKeyInterface]

Raises:
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode(e.g., unwrap, derive) the key.