API Reference¶
A Python implementation of CWT/COSE <https://python-cwt.readthedocs.io>
- cwt.encode(claims: Union[Claims, Dict[str, Any], Dict[int, Any], bytes], key: COSEKeyInterface, nonce: bytes = b'', recipients: Optional[List[RecipientInterface]] = None, signers: List[Signer] = [], tagged: bool = False) bytes [source]¶
- cwt.encode_and_mac(claims: Union[Claims, Dict[int, Any], bytes], key: COSEKeyInterface, recipients: Optional[List[RecipientInterface]] = None, tagged: bool = False) bytes [source]¶
- cwt.encode_and_sign(claims: Union[Claims, Dict[int, Any], bytes], key: Optional[COSEKeyInterface] = None, signers: List[Signer] = [], tagged: bool = False) bytes [source]¶
- cwt.encode_and_encrypt(claims: Union[Claims, Dict[int, Any], bytes], key: COSEKeyInterface, nonce: bytes = b'', recipients: Optional[List[RecipientInterface]] = None, tagged: bool = False) bytes [source]¶
- cwt.decode(data: bytes, keys: Union[COSEKeyInterface, List[COSEKeyInterface]], no_verify: bool = False) Union[Dict[int, Any], bytes] [source]¶
- 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
andnbf
(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
andnbf
.
- encode(claims: Union[Claims, Dict[str, Any], Dict[int, Any], bytes], key: COSEKeyInterface, nonce: bytes = b'', recipients: Optional[List[RecipientInterface]] = None, 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 (Optional[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: Union[Claims, Dict[int, Any], bytes], key: COSEKeyInterface, recipients: Optional[List[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 (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: Union[Claims, Dict[int, Any], bytes], key: Optional[COSEKeyInterface] = 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, thiskey
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: Union[Claims, Dict[int, Any], bytes], key: COSEKeyInterface, nonce: bytes = b'', recipients: Optional[List[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, keys: Union[COSEKeyInterface, List[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.
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.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 thekid
s in the key list given as an argument match exact.
- encode_and_mac(payload: bytes, key: COSEKeyInterface, protected: Optional[Union[dict, bytes]] = None, unprotected: Optional[dict] = None, recipients: Optional[List[RecipientInterface]] = None, external_aad: bytes = b'', out: str = '') Union[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[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’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(payload: bytes, key: Optional[COSEKeyInterface] = None, protected: Optional[Union[dict, bytes]] = None, unprotected: Optional[dict] = None, signers: List[Signer] = [], external_aad: bytes = b'', out: str = '') Union[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, thiskey
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 (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’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(payload: bytes, key: COSEKeyInterface, protected: Optional[Union[dict, bytes]] = None, unprotected: Optional[dict] = None, nonce: bytes = b'', recipients: Optional[List[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’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, CBORTag], keys: Union[COSEKeyInterface, List[COSEKeyInterface]], context: Optional[Union[List[Any], Dict[str, Any]]] = 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.
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.
- 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(params: Dict[int, Any]) COSEKeyInterface [source]¶
Creates a COSE key from a CBOR-like dictionary with numeric keys.
- Parameters
params (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.
- classmethod from_symmetric_key(key: Union[bytes, str] = b'', alg: Union[int, str] = '', kid: Union[bytes, str] = b'', key_ops: Optional[Union[List[int], List[str]]] = 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
- 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
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode the key data.
- classmethod from_jwk(data: Union[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
- 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) 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
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode the key data.
- 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) 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.
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
- 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
- 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
- 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 hcert: Optional[dict]¶
- property cnf: Optional[Union[Dict[int, Any], List[Any], str]]¶
- class cwt.Recipient[source]¶
Bases:
object
A
RecipientInterface
Builder.- classmethod new(protected: dict = {}, unprotected: dict = {}, ciphertext: bytes = b'', recipients: List[Any] = [], sender_key: Optional[COSEKeyInterface] = 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 key as COSEKey.
- Returns
A recipient object.
- Return type
- Raises
ValueError – Invalid arguments.
- classmethod from_jwk(data: Union[str, bytes, Dict[str, Any]]) RecipientInterface [source]¶
Creates a recipient from JWK-like data.
- Parameters
data (Union[str, bytes, Dict[str, Any]]) – JSON-formatted recipient data.
- Returns
A recipient object.
- Return type
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode the key data.
- classmethod from_list(recipient: List[Any]) 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
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode the key data.
- class cwt.Signer(cose_key: COSEKeyInterface, protected: Union[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: Union[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
- Raises
ValueError – Invalid arguments.
- classmethod from_jwk(data: Union[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 thekid
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 useSigner.new
.- Parameters
data (Union[str, bytes, Dict[str, Any]]) – A JWK.
- Returns
A signer information object.
- Return type
- 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]¶
Creates a signer information object (COSE_Signature) from PEM-formatted key. The
alg
in the JWK will be included in the protected header, and thekid
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 useSigner.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
- 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: Union[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
- 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: 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: Any¶
The body of the key. It can be bytes or various PublicKey/PrivateKey objects defined in
pyca/cryptography
- 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 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 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_key(context: Union[List[Any], Dict[str, Any]], material: bytes = b'', public_key: Optional[Any] = None) Any [source]¶
Derives a key with a key material or key exchange.
- Parameters
context (Union[List[Any], Dict[str, Any]]) – Context information structure for key derivation functions.
material (bytes) – A key material as bytes.
public_key – A public key for key derivation with key exchange.
- Returns
A COSE key derived.
- Return type
- Raises
NotImplementedError – Not implemented.
ValueError – Invalid arguments.
EncodeError – Failed to derive key.
- 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:
CBORProcessor
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 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 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]
- apply(key: Optional[COSEKeyInterface] = None, recipient_key: Optional[COSEKeyInterface] = None, salt: Optional[bytes] = None, context: Optional[Union[List[Any], Dict[str, Any]]] = None) COSEKeyInterface [source]¶
Applies a COSEKey as a material to prepare a MAC/encryption key 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. Therefore, it will be used by the sender of the recipient information before calling COSE.encode_* functions with the Recipient object. The key generated through this function will be set to
key
parameter of COSE.encode_* functions.- Parameters
key (Optional[COSEKeyInterface]) – The external key to be used for preparing the key.
recipient_key (Optional[COSEKeyInterface]) – The external public key provided by the recipient used for ECDH key agreement.
salt (Optional[bytes]) – A salt used for deriving a key.
context (Optional[Union[List[Any], Dict[str, Any]]]) – Context information structure.
- Returns
- A generated key or passed-throug key which is used
as
key
parameter of COSE.encode_* functions.
- Return type
- Raises
ValueError – Invalid arguments.
EncodeError – Failed to encode(e.g., wrap, derive) the key.
- extract(key: COSEKeyInterface, alg: Optional[int] = None, context: Optional[Union[List[Any], Dict[str, Any]]] = None) COSEKeyInterface [source]¶
Extracts a MAC/encryption key 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 extracting the key.
alg (Optional[int]) – The algorithm of the key extracted.
context (Optional[Union[List[Any], Dict[str, Any]]]) – Context information structure.
- Returns
- An extracted key which is used for decrypting
or verifying a payload message.
- Return type
- Raises
ValueError – Invalid arguments.
DecodeError – Failed to decode(e.g., unwrap, derive) the key.