API Reference

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

cwt.encode(claims: Union[cwt.claims.Claims, Dict[str, Any], Dict[int, Any], bytes], key: cwt.cose_key_interface.COSEKeyInterface, nonce: bytes = b'', recipients: Optional[List[cwt.recipient_interface.RecipientInterface]] = None, signers: List[cwt.signer.Signer] = [], tagged: bool = False)bytes

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.

  • 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.

cwt.encode_and_mac(claims: Union[cwt.claims.Claims, Dict[int, Any], bytes], key: cwt.cose_key_interface.COSEKeyInterface, recipients: Optional[List[cwt.recipient_interface.RecipientInterface]] = None, tagged: bool = False)bytes

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 (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.

cwt.encode_and_sign(claims: Union[cwt.claims.Claims, Dict[int, Any], bytes], key: Optional[cwt.cose_key_interface.COSEKeyInterface] = None, signers: List[cwt.signer.Signer] = [], tagged: bool = False)bytes

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 objects 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.

cwt.encode_and_encrypt(claims: Union[cwt.claims.Claims, Dict[int, Any], bytes], key: cwt.cose_key_interface.COSEKeyInterface, nonce: bytes = b'', recipients: Optional[List[cwt.recipient_interface.RecipientInterface]] = None, tagged: bool = False)bytes

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.

cwt.decode(data: bytes, key: Union[cwt.cose_key_interface.COSEKeyInterface, List[cwt.cose_key_interface.COSEKeyInterface]], no_verify: bool = False)Union[Dict[int, Any], bytes]

Verifies and decodes CWT.

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

  • key (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.

cwt.set_private_claim_names(claim_names: Dict[str, int])

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.CWT(expires_in: int = 3600, leeway: int = 60)[source]

Bases: cwt.cbor_processor.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)[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).

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,
... )
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.

encode(claims: Union[cwt.claims.Claims, Dict[str, Any], Dict[int, Any], bytes], key: cwt.cose_key_interface.COSEKeyInterface, nonce: bytes = b'', recipients: Optional[List[cwt.recipient_interface.RecipientInterface]] = None, signers: List[cwt.signer.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.

  • 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.

encode_and_mac(claims: Union[cwt.claims.Claims, Dict[int, Any], bytes], key: cwt.cose_key_interface.COSEKeyInterface, recipients: Optional[List[cwt.recipient_interface.RecipientInterface]] = None, 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 (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: Union[cwt.claims.Claims, Dict[int, Any], bytes], key: Optional[cwt.cose_key_interface.COSEKeyInterface] = None, signers: List[cwt.signer.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 objects 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: Union[cwt.claims.Claims, Dict[int, Any], bytes], key: cwt.cose_key_interface.COSEKeyInterface, nonce: bytes = b'', recipients: Optional[List[cwt.recipient_interface.RecipientInterface]] = None, 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, key: Union[cwt.cose_key_interface.COSEKeyInterface, List[cwt.cose_key_interface.COSEKeyInterface]], no_verify: bool = False)Union[Dict[int, Any], bytes][source]

Verifies and decodes CWT.

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

  • key (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.COSE(alg_auto_inclusion: int = False, kid_auto_inclusion: int = False)[source]

Bases: cwt.cbor_processor.CBORProcessor

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

classmethod new(alg_auto_inclusion: int = False, kid_auto_inclusion: int = False)[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.

encode_and_mac(payload: bytes, key: cwt.cose_key_interface.COSEKeyInterface, protected: Optional[Union[dict, bytes]] = None, unprotected: Optional[dict] = None, recipients: Optional[List[cwt.recipient_interface.RecipientInterface]] = None, external_aad: bytes = b'', out: str = '')Union[bytes, _cbor2.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[Union[dict, bytes]]) – Parameters that are to be cryptographically protected.

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

  • recipients (Optional[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: Optional[cwt.cose_key_interface.COSEKeyInterface] = None, protected: Optional[Union[dict, bytes]] = None, unprotected: Optional[dict] = None, signers: List[cwt.signer.Signer] = [], external_aad: bytes = b'', out: str = '')Union[bytes, _cbor2.CBORTag][source]

Encodes data with signing.

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

  • key (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[Union[dict, bytes]]) – Parameters that are to be cryptographically protected.

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

  • signers (Optional[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: cwt.cose_key_interface.COSEKeyInterface, protected: Optional[Union[dict, bytes]] = None, unprotected: Optional[dict] = None, nonce: bytes = b'', recipients: Optional[List[cwt.recipient_interface.RecipientInterface]] = None, external_aad: bytes = b'', out: str = '')bytes[source]

Encodes data with encryption.

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

  • key (COSEKeyInterface) – A COSE key as an encryption key.

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

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

  • nonce (bytes) – A nonce for encryption.

  • recipients (Optional[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.

decode(data: Union[bytes, _cbor2.CBORTag], key: Optional[Union[cwt.cose_key_interface.COSEKeyInterface, List[cwt.cose_key_interface.COSEKeyInterface]]] = None, materials: Optional[List[dict]] = None, external_aad: bytes = b'')bytes[source]

Verifies and decodes COSE data.

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

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

  • materials (Optional[List[dict]]) – A list of key materials to be used to derive an encryption key.

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

Returns

A byte string of decoded payload.

Return type

bytes

Raises
  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode data.

  • VerifyError – Failed to verify data.

class cwt.COSEKey[source]

Bases: object

A COSEKeyInterface Builder.

static new(cose_key: Dict[int, Any])cwt.cose_key_interface.COSEKeyInterface[source]

Create a COSE key from a CBOR-like dictionary with numeric keys.

Parameters

cose_key (Dict[int, Any]) – A CBOR-like dictionary with numeric keys of a COSE key.

Returns

A COSE key object.

Return type

COSEKeyInterface

Raises

ValueError – Invalid arguments.

classmethod from_symmetric_key(key: Union[bytes, str] = b'', alg: Union[int, str] = 'HMAC 256/256', kid: Union[bytes, str] = b'', key_ops: Optional[Union[List[int], List[str]]] = None)cwt.cose_key_interface.COSEKeyInterface[source]

Create 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)cwt.cose_key_interface.COSEKeyInterface[source]

Create 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: Union[str, bytes, Dict[str, Any]])cwt.cose_key_interface.COSEKeyInterface[source]

Create 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: Union[str, bytes], alg: Union[int, str] = '', kid: Union[bytes, str] = b'', key_ops: Optional[Union[List[int], List[str]]] = None)cwt.cose_key_interface.COSEKeyInterface[source]

Create 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.EncryptedCOSEKey[source]

Bases: cwt.cbor_processor.CBORProcessor

An encrypted COSE key.

static from_cose_key(key: cwt.cose_key_interface.COSEKeyInterface, encryption_key: cwt.cose_key_interface.COSEKeyInterface, nonce: bytes = b'', tagged: bool = False)Union[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.

Returns

A COSE_Encrypt0 structure of the target COSE key.

Return type

List[Any]

Raises
  • ValueError – Invalid arguments.

  • EncodeError – Failed to encrypt the COSE key.

static to_cose_key(key: List[Any], encryption_key: cwt.cose_key_interface.COSEKeyInterface)cwt.cose_key_interface.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]

Create 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: Union[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: Optional[str]
property sub: Optional[str]
property aud: Optional[str]
property exp: Optional[int]
property nbf: Optional[int]
property iat: Optional[int]
property cti: Optional[str]
property cnf: Optional[Union[Dict[int, Any], List[Any], str]]
get(key: Union[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]
class cwt.Recipient[source]

Bases: object

A RecipientInterface Builder.

classmethod new(protected: dict = {}, unprotected: dict = {}, ciphertext: bytes = b'', recipients: List[Any] = [], key_ops: List[int] = [], key: bytes = b'')cwt.recipient_interface.RecipientInterface[source]

Create 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.

Returns

A recipient object.

Return type

RecipientInterface

Raises

ValueError – Invalid arguments.

classmethod from_json(data: Union[str, bytes, Dict[str, Any]])cwt.recipient_interface.RecipientInterface[source]

Create a recipient from JSON-formatted recipient 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: cwt.cose_key_interface.COSEKeyInterface, protected: Union[Dict[int, Any], bytes], unprotected: Dict[int, Any], signature: bytes = b'')[source]

Bases: cwt.cbor_processor.CBORProcessor

A Signer information.

property cose_key: cwt.cose_key_interface.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: cwt.cose_key_interface.COSEKeyInterface, protected: Union[dict, bytes] = {}, unprotected: dict = {}, signature: bytes = b'')[source]

Create a signer information object (COSE_Signature).

Parameters
  • 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: Union[str, bytes, Dict[str, Any]])[source]

Create 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: Union[str, bytes], alg: Union[int, str] = '', kid: Union[bytes, str] = b'')[source]

Create 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.

exception cwt.CWTError[source]

Bases: Exception

Base class for all exceptions.

exception cwt.EncodeError[source]

Bases: cwt.exceptions.CWTError

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

exception cwt.DecodeError[source]

Bases: cwt.exceptions.CWTError

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

exception cwt.VerifyError[source]

Bases: cwt.exceptions.CWTError

An Exception occurred when a verification process failed.

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

Bases: cwt.cbor_processor.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: Optional[bytes]

The key identifier.

property alg: Optional[int]

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: Optional[bytes]

Base IV to be xor-ed with Partial IVs.

property key: bytes

The body of the key as bytes.

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.

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.

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

Bases: cwt.cose_key_interface.COSEKeyInterface

The interface class for a COSE Recipient.

__init__(protected: Optional[Dict[int, Any]] = None, unprotected: Optional[Dict[int, Any]] = 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 key: bytes

The body of the key as bytes.

property protected: Dict[int, Any]

The parameters that are to be cryptographically protected.

property unprotected: Dict[int, Any]

The parameters that are not cryptographically protected.

property ciphertext: bytes

The ciphertext encoded as bytes

property recipients: Optional[List[Any]]

The list of recipient information structures.

to_list()List[Any][source]

Returns the recipient information as a COSE recipient structure.

Returns

The recipient structure.

Return type

List[Any]

set_key(key: bytes)[source]

Sets a key.

Parameters

key (bytes) – The key as bytes.

derive_key(material: bytes, context: Union[List[Any], Dict[str, Any]])cwt.cose_key_interface.COSEKeyInterface[source]

Derives a key from a key material.

Parameters
  • material (bytes) – A key material.

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

Returns

A COSE key derived.

Return type

COSEKeyInterface

Raises
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • EncodeError – Failed to derive key.

verify_key(material: bytes, expected_key: bytes, context: Union[List[Any], Dict[str, Any]])[source]

Verifies a key with a key material and an expected key.

Parameters
  • material (bytes) – A key material.

  • expected_key (bytes) – A byte string of the expected key.

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

Raises
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • VerifyError – Failed to verify the key.

wrap_key(key_to_wrap: bytes)[source]

Wraps a key and keeps it internally as the ciphertext.

Parameters

key_to_wrap (bytes) – A key to be wrapped.

Raises
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • EncodeError – Failed to encode(wrap) key.

unwrap_key(alg: int)cwt.cose_key_interface.COSEKeyInterface[source]

Unwraps the key stored as the ciphertext.

Parameters

alg (int) – The algorithm of the wrapped key.

Returns

An unwrapped key.

Return type

COSEKeyInterface

Raises
  • NotImplementedError – Not implemented.

  • ValueError – Invalid arguments.

  • DecodeError – Failed to decode(unwrap) the key.