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, str], key: cwt.cose_key.COSEKey, nonce: bytes = b'', tagged: bool = False, recipients: Optional[List[cwt.recipient.Recipient]] = None) → 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, str]) – A CWT claims object, or a JWT claims object, text string or byte string.
key (COSEKey) – A COSE key used to generate a MAC for the claims.
recipients (List[Recipient]) – 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.COSEKey, tagged: bool = False, recipients: Optional[List[cwt.recipient.Recipient]] = None) → bytes¶ Encodes with MAC.
- Parameters
claims (Union[Claims, Dict[int, Any], bytes]) – A CWT claims object or byte string.
key (COSEKey) – A COSE key used to generate a MAC for the claims.
recipients (List[Recipient]) – 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: Union[cwt.cose_key.COSEKey, List[cwt.cose_key.COSEKey]], tagged: bool = False) → bytes¶ Encodes CWT with signing.
- Parameters
- 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.COSEKey, nonce: bytes = b'', tagged: bool = False, recipients: Optional[List[cwt.recipient.Recipient]] = None) → bytes¶ Encodes CWT with encryption.
- Parameters
claims (Claims, Union[Dict[int, Any], bytes]) – A CWT claims object or byte
string. –
key (COSEKey) – A COSE key used to encrypt the claims.
nonce (bytes) – A nonce for encryption.
recipients (List[Recipient]) – 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.COSEKey, List[cwt.cose_key.COSEKey]], no_verify: bool = False) → Dict[int, Any]¶ Verifies and decodes CWT.
- Parameters
- Returns
A byte string of the decoded CWT.
- Return type
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. This function call is redirected to the internal
ClaimsBuilder
’sset_private_claim_names
directly. The definitions will be used inencode
when it is called with JSON-based claims.- Parameters
claims (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.
- Raises
ValueError – Invalid arguments.
-
class
cwt.
CWT
(options: Optional[Dict[str, Any]] = None)[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¶
-
__init__
(options: Optional[Dict[str, Any]] = None)[source]¶ Constructor.
- Parameters
options (Optional[Dict[str, Any]]) – Options for the initial configuration of CWT. At this time,
expires_in
(default value:3600
) andleaway
(default value:60
) are only supported. See alsoexpires_in
,leeway
.
Examples
>>> from cwt import CWT, claims, cose_key >>> ctx = CWT({"expires_in": 3600*24, "leeway": 10}) >>> key = cose_key.from_symmetric_key("mysecret") >>> token = ctx.encode_and_mac( ... claims.from_json({"iss": "coaps://as.example", "sub": "dajiaji", "cti": "123"}), ... key, ... )
-
property
expires_in
¶ The default lifetime in seconds of CWT. If exp is not found in claims, this value will be used with current time.
-
property
leeway
¶ The default leeway in seconds for validating
exp
andnbf
.
-
encode
(claims: Union[cwt.claims.Claims, Dict[str, Any], Dict[int, Any], bytes, str], key: cwt.cose_key.COSEKey, nonce: bytes = b'', tagged: bool = False, recipients: Optional[List[cwt.recipient.Recipient]] = None) → 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, str]) – A CWT claims object, or a JWT claims object, text string or byte string.
key (COSEKey) – A COSE key used to generate a MAC for the claims.
recipients (List[Recipient]) – 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.COSEKey, tagged: bool = False, recipients: Optional[List[cwt.recipient.Recipient]] = None) → bytes[source]¶ Encodes with MAC.
- Parameters
claims (Union[Claims, Dict[int, Any], bytes]) – A CWT claims object or byte string.
key (COSEKey) – A COSE key used to generate a MAC for the claims.
recipients (List[Recipient]) – 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: Union[cwt.cose_key.COSEKey, List[cwt.cose_key.COSEKey]], tagged: bool = False) → bytes[source]¶ Encodes CWT with signing.
- Parameters
- 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.COSEKey, nonce: bytes = b'', tagged: bool = False, recipients: Optional[List[cwt.recipient.Recipient]] = None) → bytes[source]¶ Encodes CWT with encryption.
- Parameters
claims (Claims, Union[Dict[int, Any], bytes]) – A CWT claims object or byte
string. –
key (COSEKey) – A COSE key used to encrypt the claims.
nonce (bytes) – A nonce for encryption.
recipients (List[Recipient]) – 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.COSEKey, List[cwt.cose_key.COSEKey]], no_verify: bool = False) → Dict[int, Any][source]¶ Verifies and decodes CWT.
- Parameters
- Returns
A byte string of the decoded CWT.
- Return type
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. This function call is redirected to the internal
ClaimsBuilder
’sset_private_claim_names
directly. The definitions will be used inencode
when it is called with JSON-based claims.- Parameters
claims (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.
- Raises
ValueError – Invalid arguments.
-
-
class
cwt.
COSE
(options: Optional[Dict[str, Any]] = None)[source]¶ Bases:
cwt.cbor_processor.CBORProcessor
A COSE (CBOR Object Signing and Encryption) Implementaion built on top of cbor2.
cwt.cose_key
is a global object of this class initialized with default settings.-
__init__
(options: Optional[Dict[str, Any]] = None)[source]¶ Constructor.
At the current implementation, any
options
will be ignored.
-
encode_and_mac
(protected: Dict[int, Any], unprotected: Dict[int, Any], payload: Union[Dict[int, Any], bytes], key: cwt.cose_key.COSEKey, recipients: Optional[List[cwt.recipient.Recipient]] = None, out: str = '') → Union[bytes, _cbor2.CBORTag][source]¶ Encodes data with MAC.
- Parameters
protected (Dict[int, Any]) – Parameters that are to be cryptographically protected.
unprotected (Dict[int, Any]) – Parameters that are not cryptographically protected.
payload (Union[Dict[int, Any], bytes]) – A content to be MACed.
key (COSEKey) – A COSE key as a MAC Authentication key.
recipients (Optional[List[Recipient]]) – A list of recipient information structures.
out (str) –
An output format. Only
"cbor2/CBORTag"
can be used. If"cbor2/CBORTag"
is specified. This function will return encoded data as cbor2’sCBORTag
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
(protected: Dict[int, Any], unprotected: Dict[int, Any], payload: Union[Dict[int, Any], bytes], key: Union[cwt.cose_key.COSEKey, List[cwt.cose_key.COSEKey]], out: str = '') → Union[bytes, _cbor2.CBORTag][source]¶ Encodes data with signing.
- Parameters
protected (Dict[int, Any]) – Parameters that are to be cryptographically protected.
unprotected (Dict[int, Any]) – Parameters that are not cryptographically protected.
payload (Union[Dict[int, Any], bytes]) – A content to be signed.
key (Union[COSEKey, List[COSEKey]]) – One or more COSE keys as signing keys.
out (str) –
An output format. Only
"cbor2/CBORTag"
can be used. If"cbor2/CBORTag"
is specified. This function will return encoded data as cbor2’sCBORTag
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
(protected: Dict[int, Any], unprotected: Dict[int, Any], payload: Union[Dict[int, Any], bytes], key: cwt.cose_key.COSEKey, nonce: bytes = b'', recipients: Optional[List[cwt.recipient.Recipient]] = None, out: str = '') → bytes[source]¶ Encodes data with encryption.
- Parameters
protected (Dict[int, Any]) – Parameters that are to be cryptographically protected.
unprotected (Dict[int, Any]) – Parameters that are not cryptographically protected.
payload (Union[Dict[int, Any], bytes]) – A content to be encrypted.
key (COSEKey) – A COSE key as an encryption key.
nonce (bytes) – A nonce for encryption.
recipients (Optional[List[Recipient]]) – A list of recipient information structures.
out (str) –
An output format. Only
"cbor2/CBORTag"
can be used. If"cbor2/CBORTag"
is specified. This function will return encoded data as cbor2’sCBORTag
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: Union[cwt.cose_key.COSEKey, List[cwt.cose_key.COSEKey]]) → Dict[int, Any][source]¶ Verifies and decodes COSE data.
- Parameters
data (Union[bytes, CBORTag]) – A byte string or cbor2.CBORTag of an encoded data.
key (COSEKey) – A COSE key to verify and decrypt the encoded data.
- Returns
A decoded CBOR-like object.
- Return type
Dict[int, Any]
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode data.
VerifyError – Failed to verify data.
-
-
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, 'exp': 4, 'hcert': - 260, 'iat': 6, 'iss': 1, 'nbf': 5, 'sub': 2})[source]¶ Bases:
object
A class for handling CWT Claims like JWT claims.
-
property
iss
¶
-
property
sub
¶
-
property
aud
¶
-
property
exp
¶
-
property
nbf
¶
-
property
iat
¶
-
property
cti
¶
-
property
cnf
¶
-
property
-
class
cwt.
ClaimsBuilder
(options: Optional[Dict[str, Any]] = None)[source]¶ Bases:
object
CBOR Web Token (CWT) Claims Builder.
cwt.claims
is a global object of this class initialized with default settings.-
__init__
(options: Optional[Dict[str, Any]] = None)[source]¶ Constructor.
At the current implementation, any
options
will be ignored.
-
from_dict
(claims: Dict[int, Any]) → cwt.claims.Claims[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.
- Returns
A CWT claims object.
- Return type
- Raises
ValueError – Invalid arguments.
-
from_json
(claims: Union[str, bytes, Dict[str, Any]]) → cwt.claims.Claims[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.
- Returns
A CWT claims object.
- Return type
- Raises
ValueError – Invalid arguments.
-
set_private_claim_names
(claim_names: Dict[str, int])[source]¶ Sets private claim definitions. The definitions will be used in
from_json
.- Parameters
claims (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.
- Raises
ValueError – Invalid arguments.
-
-
class
cwt.
COSEKey
(cose_key: Dict[int, Any])[source]¶ Bases:
object
The interface class for a COSE Key used for MAC, signing/verifying and encryption/decryption.
-
__init__
(cose_key: Dict[int, Any])[source]¶ Constructor.
- Parameters
cose_key (Dict[int, Any]) – A COSE key formatted to a CBOR-like dictionary.
-
property
key
¶ A body of the symmetric key.
-
property
kty
¶ Identification of the key type.
-
property
kid
¶ A key identification value.
-
property
alg
¶ An algorithm that is used with the key.
-
property
crv
¶ A curve of the key type.
-
property
key_ops
¶ Restrict set of permissible operations.
-
property
base_iv
¶ Base IV to be xor-ed with Partial IVs.
-
to_dict
() → Dict[int, Any][source]¶ Returns a CBOR-like structure (Dict[int, Any]) of the COSE key.
- Returns
A CBOR-like structure of the COSE key.
- Return type
Dict[int, Any]
-
generate_nonce
() → bytes[source]¶ Returns a nonce with a size suitable for the algorithm. This function will be called internally in
CWT
when no nonce is specified by the application. This function adoptssecrets.token_bytes()
to generate a nonce. If you do not want to use it, you should explicitly set a nonce toCWT
functions (e.g.,encode_and_encrypt
).- Returns
A byte string of a 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
A 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
A 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
A 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
A byte string of the decrypted data.
- Return type
bytes
- Raises
NotImplementedError – Not implemented.
ValueError – Invalid arguments.
DecodeError – Failed to decrypt the message.
-
-
class
cwt.
KeyBuilder
(options: Optional[Dict[str, Any]] = None)[source]¶ Bases:
cwt.cbor_processor.CBORProcessor
A
COSEKey
Builder.-
__init__
(options: Optional[Dict[str, Any]] = None)[source]¶ Constructor.
At the current implementation, any
options
will be ignored.
-
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.COSEKey[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
- Raises
ValueError – Invalid arguments.
-
from_dict
(cose_key: Dict[int, Any]) → cwt.cose_key.COSEKey[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
- Raises
ValueError – Invalid arguments.
-
from_bytes
(key_data: bytes) → cwt.cose_key.COSEKey[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
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode the key data.
-
from_jwk
(data: Union[str, bytes, Dict[str, Any]]) → cwt.cose_key.COSEKey[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
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode the key data.
-
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.COSEKey[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.KeyBuilder.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
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode the key data.
-
from_encrypted_cose_key
(key: List[Any], encryption_key: cwt.cose_key.COSEKey) → cwt.cose_key.COSEKey[source]¶ Returns an encrypted COSE key formatted to COSE_Encrypt0 structure.
- Parameters
key – COSEKey: A key formatted to COSE_Encrypt0 structure to be decrypted.
encryption_key – COSEKey: An encryption key to decrypt the target COSE key.
- Returns
A COSE_Encrypt0 structure of the target COSE key.
- Return type
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode the COSE key.
VerifyError – Failed to verify the COSE key.
-
to_encrypted_cose_key
(key: cwt.cose_key.COSEKey, encryption_key: cwt.cose_key.COSEKey, nonce: bytes = b'', tagged: bool = False) → Union[List[Any], bytes][source]¶ Returns an encrypted COSE key formatted to COSE_Encrypt0 structure.
- Parameters
key – COSEKey: A key to be encrypted.
encryption_key – COSEKey: 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.
-
-
class
cwt.
Recipient
(protected: Union[bytes, Dict[int, Any]] = {}, unprotected: Dict[int, Any] = {}, ciphertext: bytes = b'', recipients: List[Any] = [])[source]¶ Bases:
cwt.cbor_processor.CBORProcessor
A COSE Recipient.
-
property
protected
¶
-
property
unprotected
¶
-
property
alg
¶
-
property
kid
¶
-
property
ciphertext
¶
-
property
recipients
¶
-
property
-
exception
cwt.
EncodeError
[source]¶ Bases:
cwt.exceptions.CWTError
An Exception occurred when a CWT/COSE encoding process failed.