pytrustplatform package¶
CA certificate creation¶
CA certificate creation utilities
- pytrustplatform.ca_create.add_signer_extensions(builder, public_key=None, authority_cert=None)¶
Add signer extensions to certificate builder :param builder: certificate builder :param public_key: public key to use (default: taken from builder) :param authority_cert: optional authority certificate
- pytrustplatform.ca_create.ca_create_root(root_ca_key_path, root_ca_cert_path, force=False, org_name=None, common_name=DEFAULT_ROOT_COMMON_NAME, country=None)¶
Creates a CA Root Certificate :param root_ca_key_path: path to look for private key (or place key if created) :param root_ca_cert_path: path to store certificate :param force: Force re-creation of existing certificate :param org_name: Specify Organization Name attribute :param common_name: Specify Common Name attribute
- pytrustplatform.ca_create.ca_create_signer(signer_ca_csr_path, signer_ca_cert_path, root_ca_key_path, root_ca_cert_path, force=False)¶
Create signer certificate :param signer_ca_csr_path: path to signer CA Certificate Signing Request :param signer_ca_cert_path: path to store signer CA certificate :param root_ca_key_path: path to look for private key :param root_ca_cert_path: path to root CA certificate :param force: Force re-creation of existing certificate
- pytrustplatform.ca_create.ca_create_signer_csr(signer_ca_key_path, signer_ca_csr_path, force=False, org_name=DEFAULT_ORGANIZATION_NAME, common_name=DEFAULT_SIGNER_COMMON_NAME, country=None)¶
Create a signer Certificate Signing Request (CSR) :param signer_ca_key_path: path to signer CA key :param signer_ca_csr_path: path to signer CA Certificate Signing Request :param force: Force re-creation of existing certificate :param org_name: Specify Organization Name attribute :param common_name: Specify Common Name attribute
- pytrustplatform.ca_create.load_certificate(certificate_path)¶
Loads a certificate from file :param certificate_path: path to file to load :return: certificate data
- pytrustplatform.ca_create.load_csr(csr_path)¶
Loads a CSR from file :param csr_path: path to request to load
- pytrustplatform.ca_create.load_key(filename)¶
Loads an existing key from file :param filename: key to load :return: key loaded
- pytrustplatform.ca_create.load_or_create_key(filename, force_create=False)¶
Attempts to load a key from file If the file does not exist, a new key is created and written to file. :param filename: file to attempt to open or create :param force: create a new key even if it exists already :return: key content
- pytrustplatform.ca_create.random_cert_sn(size)¶
Create a positive, non-trimmable serial number for X.509 certificates :param size: size in bytes :return: random serial number
- pytrustplatform.ca_create.save_certificate(filename, certificate)¶
Writes a certificate to file using PEM encoding :param filename: file to write to :param certificate: certificate to write
- pytrustplatform.ca_create.save_key(filename, key)¶
Writes a key to file using PEM encoding :param filename: file to write to :param key: key to write
Get certificate data¶
Helper functions for fetching data from a certificate
- pytrustplatform.cert_get_data.cert_get_common_name(filename)¶
Get Subject Common Name from a certificate passed in by filename
- Parameters:
filename (str) – Certificate file
- Returns:
Subject Common Name from certificate
- Return type:
str
- pytrustplatform.cert_get_data.cert_get_common_name_from_pem(certificate)¶
Get Subject Common Name from certificate passed in as a PEM string
- Parameters:
certificate (str or bytes) – Certificate in PEM format
- Returns:
Subject Common Name from certificate
- Return type:
str
- pytrustplatform.cert_get_data.cert_get_skid(filename)¶
Create Subject key identifier from a certificate.
- Parameters:
filename (str) – Certificate file
- Returns:
ASCII hex encoded subject key identifier
- Return type:
str
- pytrustplatform.cert_get_data.create_cert_fingerprint(filename)¶
Create fingerprint of certificate
- Parameters:
filename (str) – Certificate file
- Returns:
ASCII hex encoded fingerprint
- Return type:
str
Compressed certificate decoder¶
Decodes compressed certificates from ECC
- class pytrustplatform.compressed_cert_decoder.CertificateRepresentation(compressed_certificate_data)¶
Bases:
object
Representation of a certificate
- build_serialnumber(pubkey=None, dev_sn_number=None)¶
Builds a serial number :param pubkey: public key to use :param dev_sn_number: serial number to use
- log()¶
Log some fields
- class pytrustplatform.compressed_cert_decoder.CompressedCertificateData¶
Bases:
object
Compressed certificate data provider
- read_from_kit(firmware_driver)¶
Read data from a kit Do not read slot 5 - see function read_from_kit_slot5
- Parameters:
firmware_driver – Protocol driver instance for communicating with firmware on the MCU
- read_from_kit_slot5(firmware_driver)¶
Read slot 5 data from a kit Slot 5 is only readable if the ECC is not in [MAH1H, MAH4I]
- Parameters:
firmware_driver – Protocol driver instance for communicating with firmware on the MCU
- class pytrustplatform.compressed_cert_decoder.DeviceCertificateRepresentation(compressed_certificate_data)¶
Bases:
CertificateRepresentation
Representation of a device certificate
- class pytrustplatform.compressed_cert_decoder.SignerCertificateRepresentation(compressed_certificate_data)¶
Bases:
CertificateRepresentation
Representation of a signer certificate
- pytrustplatform.compressed_cert_decoder.create_key_identifier(pubkey)¶
Create the key identifier.
- Parameters:
pubkey (bytearray) – Public key from which the key identifier should be derived.
Device certificate builder¶
Device certificate builder
This module supports building device certificates from device Certificate Signing Requests (CSR)
- pytrustplatform.device_cert_builder.build_device_cert(firmware_driver, signer_ca_cert_file, signer_ca_key_file, csr_filename, cert_filename, force=False)¶
Build device certificate
Uses serial number from ECC and Certificate Signing Request (CSR) to generate a device certificate The certificate is written to file and returned
- Parameters:
firmware_driver – Protocol driver instance for communicating with firmware on the MCU
signer_ca_cert_file (str) – File containing signer Certificate Authority certificate
signer_ca_key_file (str) – File containing signer Certificate Authority private key
csr_filename (str) – Name of file to write the generated CSR to.
cert_filename (str) – Name of file to write the generated certificate to
force (bool) – Force creating new certificate overwriting pre-existing output file
- Returns:
Device certificate
- Return type:
cryptography.x509.Certificate
object- Raises:
PytrustCertificateError – If something is wrong with the CSR signature
- pytrustplatform.device_cert_builder.build_device_csr(firmware_driver, csr_filename, common_name, force=False, org_name=None, country=None)¶
Build device Certificate Signing Request
Build a device CSR from a template. The CSR is used when building a device certificate.
- Parameters:
firmware_driver – Protocol driver instance for communicating with firmware on the MCU
csr_filename (str) – Name of file to write the generated CSR to.
common_name – Subject Common Name (CN) to use in the CSR. This is typically a unique name or ID for this device
org_name – Subject Organization Name (O) to use in this CSR. If not specified, predefined ORG_NAME will be used.
force (bool) – Force creating new certificate overwriting pre-existing output file
- Returns:
Device Certificate Signing Request
- Return type:
class:cryptography.x509.CertificateSigningRequest object
- pytrustplatform.device_cert_builder.device_cert_sn(size, builder)¶
Generate Certificate serial number
Cert serial number is the SHA256(Subject public key + Encoded dates) :param size: Serial number length in bytes :type size: int :param builder: x509 certificate builder :type builder:
cryptography.x509.CertificateBuilder
object :return: Certificate serial number :rtype: int
ECC certificate builder¶
Certificate builder for ATECC608 certificates
This module supports building certificates from templates and data fetched from ECC compressed certificates
- class pytrustplatform.ecc_cert_builder.EccCertificateBuilder(cert_pem)¶
Bases:
object
Certificate builder for ATECC608 certificates.
- add_signature(signature)¶
- set_pubkey(pubkey)¶
TBD the from_coords does not result in the expected outcome so we create the raw DER encoding that we load into the ECPointString class.
- ecpoint = ECPointBitString().from_coords(int.from_bytes(pubkey[0:33], byteorder=’big’, signed=False),
int.from_bytes(pubkey[33:], byteorder=’big’, signed=False))
- set_serial_number(serial)¶
Sets the serial number in the certificate being built
- set_validity_dates(validity_not_before, validity_not_after)¶
Set validity dates in certificate.
- Parameters:
validity_not_before (datetime) – Date and time where certificate should note be valid before
validity_not_after (datetime) – Date and time where certificate should note be valid after
- class pytrustplatform.ecc_cert_builder.Mah1hDeviceCertificateBuilder(cert_pem)¶
Bases:
EccCertificateBuilder
Build device certificate for ATECC608A-MAH1H
- build(data)¶
Builds the certificate
- set_authority_key_identifier(akid)¶
Sets the authority key identifier in the certificate being built
- set_issuer(signer_id)¶
Sets the issuer signer ID in the certificate being built
- class pytrustplatform.ecc_cert_builder.Mah1hSignerCertificateBuilder(cert_pem)¶
Bases:
EccCertificateBuilder
Build signer certificate for ATECC608A-MAH1H
- build(data)¶
Builds the certificate
- set_subject(signer_id)¶
Sets the subject in the certificate being built
- set_subject_key_identifier(skid)¶
Sets the subject key identifier in the certificate being built
- set_validity_dates(validity_not_before, validity_not_after)¶
Set validity dates in certificate.
- Parameters:
validity_not_before (datetime) – Date and time where certificate should note be valid before
validity_not_after (datetime) – Date and time where certificate should note be valid after
- class pytrustplatform.ecc_cert_builder.Mah4iDeviceCertificateBuilder(cert_pem)¶
Bases:
TngDeviceCertificateBuilder
- build(data)¶
Builds the certificate
- class pytrustplatform.ecc_cert_builder.Mah4iSignerCertificateBuilder(cert_pem)¶
Bases:
TngSignerCertificateBuilder
Unused
- class pytrustplatform.ecc_cert_builder.TngDeviceCertificateBuilder(cert_pem)¶
Bases:
EccCertificateBuilder
- build(data)¶
Builds the certificate
- set_authority_key_identifier(akid, extension_index=4)¶
Sets the authority key identifier in the certificate being built
- set_issuer(signer_id)¶
Sets the issuer in the certificate being built
- set_mac_address(eui48='FFFFFFFFFFFFFFFF')¶
Sets the MAC address in the certificate being built
- set_subject(serial_number)¶
Sets the subject in the certificate being built
- set_subject_key_identifier(skid, extension_index=3)¶
Sets the subject key identifier in the certificate being built
- class pytrustplatform.ecc_cert_builder.TngSignerCertificateBuilder(cert_pem)¶
Bases:
EccCertificateBuilder
- build(data)¶
Builds the certificate
- set_subject(signer_id)¶
Sets the subject in the certificate being built
- set_subject_key_identifier(skid)¶
Sets the subject key identifier in the certificate being built
- pytrustplatform.ecc_cert_builder.build_certs_from_ecc(firmware_driver, signer_cert_filename=None, device_cert_filename=None, device_cert_template=None, signer_cert_template=None, force=False)¶
Build device and signer certificates from compressed certificates read out from the ECC device
- Parameters:
firmware_driver – Protocol driver instance for communicating with firmware on the MCU
signer_cert_filename (str) – Name of file to write the generated signer certificate to. Optional. If set to None no certificate file will be created.
device_cert_filename (str) – Name of file to write the generated device certificate to. Optional. If set to None no certificate will be created
device_cert_template (str (path)) – File with device certificate template. Optional. If set to None a built in template will be used
signer_cert_template (str (path)) – File with signer certificate template. Optional. If set to None a built in template will be used
force (bool) – Force creating new certificates overwriting pre-existing output file
- Returns:
device_certificate, signer_certificate
- Return type:
cryptography.x509.Certificate
objects
ECC type utilities¶
Helper for differentiating between various types of ECC devices
- pytrustplatform.ecc_types.classify_ecc_type(ecc_serial_number, ecc_otp_values=None)¶
Classifies the ECC type based on input parameters, returning a list of likely matches. Possible types to classify: Trust&Go: ‘tng’ Trust&Flex: ‘tflx’ Trust custom: ‘custom’ MAH4I: ‘mah4i’ MAH1H: ‘mah1h’
- Parameters:
ecc_serial_number – serial number read from the ECC
ecc_otp_values – optional OTP area contents
- Returns:
a list of likely matches
Verification certificate builder¶
Verification certificate builder
This module supports building verification certificates typically used for signer Certificate Authority (CA) verification
- pytrustplatform.verification_cert_builder.build_verification_cert(signer_ca_cert_file, signer_ca_key_file, subject_cn, verification_cert_filename)¶
Build verification certificate
The verification certificate is typically used to verify a Certificate Authority (CA) when registering the CA in a cloud provider. The verification certificate is written to file.
- Parameters:
signer_ca_cert_file (str) – File containing signer Certificate Authority certificate
signer_ca_key_file (str) – File containing signer Certificate Authority private key
subject_cn – Subject Common Name (CN) for the verification certificate. For AWS this is the registration code required when registering a CA certificate (signer)
verification_cert_filename (str) – Name (path) of file to write verification certificate to
- Returns:
Verification certificate object
- Return type:
cryptography.x509.Certificate
object
Manifest functions¶
pytrustplatform manifest functions
- pytrustplatform.manifest.manifest_functions.create_manifest_from_certs(manifest, manifest_signer_cert, manifest_signer_key, device_cert, signer_cert, ecc_type=None)¶
Create a manifest based on device and signer certificates
- Parameters:
manifest (str) – Manifest file name
manifest_signer_cert (str) – Manifest signer certificate path
manifest_signer_key (str) – Manifest signer private key path
device_cert (str) – Device certificate path
signer_cert (str) – Signer certificate path
ecc_type (str) – Type of secure element. Last part of the order code e.g. TNGOTLS or TFLXTLS
- pytrustplatform.manifest.manifest_functions.create_manifest_from_secure_element(manifest, manifest_signer_cert, manifest_signer_key, kit_info)¶
Create a manifest from a secure element.
- Parameters:
manifest (str) – Manifest file name
manifest_signer_cert (str) – Manifest signer certificate path
manifest_signer_key (str) – Manifest signer private key path
kit_info – Kit information from pykitcommander
- pytrustplatform.manifest.manifest_functions.extract_certificates(manifest, unique_id: None = None, key_index: int = 0, cert_indexes=None, file_names='common-name', outdir=None)¶
Extracts certificates from secure elements in a manifest
- Parameters:
manifest (str, list, bytes, bytearray) – Manifest
unique_id (str, optional) – If provided the certificates will only be extracted for the secure element with the same unique ID, defaults to None
key_index (int, optional) – Certificates correspond to a key in the secure element and this index defines for which key the certificates should be extracted, defaults to 0
cert_indexes (list, optional) – Defines which certificates in the chain should be extracted. Index 0 is the first certificate in the chain (device certificate), subsequent certificates will be the “CA” certificates used to verify the previous one (e.g. index 1 is the signer certificate that can verify the device certificate at index 0. If several certificates should be extracted add their index to the list e.g. [0,1], defaults to [0]
file_names (str, optional) – File name of the extracted certificates, either “common-name” which uses the certificate subject common name as file name, or “fingerprint” which uses the fingerprint of the certificate as file name (SHA256 of cert in DER format), defaults to “common-name”
outdir (str, optional) – Output folder where extracted certificates should be stored, defaults to None which will put the certificate in the folder from which the script was executed.
- pytrustplatform.manifest.manifest_functions.extract_certificates_from_secure_element(secure_element, key_index=0, cert_indexes=None, file_names='common-name', outdir=None)¶
Extract certificates from a secure element
Fetches certificates from a secure element and saves them in a directory.
- Parameters:
secure_element (SecureElement or any subclass thereof) – Secure element
key_index (int, optional) – Certificates correspond to a key in the secure element and this index defines for which key the certificates should be extracted, defaults to 0
cert_indexes (list, optional) – Defines which certificates in the chain should be extracted. Index 0 is the first certificate in the chain (device certificate), subsequent certificates will be the “CA” certificates used to verify the previous one (e.g. index 1 is the signer certificate that can verify the device certificate at index 0. If several certificates should be extracted add their index to the list e.g. [0,1], defaults to [0]
file_names (str, optional) – File name of the extracted certificates, either “common-name” which uses the certificate subject common name as file name, or “fingerprint” which uses the fingerprint of the certificate as file name (SHA256 of cert in DER format), defaults to “common-name”
outdir (str, optional) – Output folder where extracted certificates should be stored, defaults to None which will put the certificate in the folder from which the script was executed.
- pytrustplatform.manifest.manifest_functions.get_secure_element(manifest, secure_element_id)¶
Get a secure element from manifest by its unique ID
- Parameters:
manifest (str) – Manifest file.
id (str) – Unique ID of the secure element (e.g. serial number of ATECC608)
- pytrustplatform.manifest.manifest_functions.list_secure_element_ids(manifest)¶
List secure elements unique ID from manifest
- Parameters:
manifest (str) – Manifest file
- Returns:
list of elements
- Return type:
list of str
- pytrustplatform.manifest.manifest_functions.list_secure_elements(manifest)¶
List secure elements from manifest
- Parameters:
manifest (list, str, bytes, bytearray) – Manifest to parse for secure elements. Json encoded data (str, bytes, bytearray) or already decoded data (str).
- Returns:
list of elements
- Return type:
list of str
Manifest library¶
Microchip Secure Element Manifest library.
Main library features: * building of manifests * verifying signed secured elements * searching in manifests * extracting secured elements from manifest
- class pytrustplatform.manifest.manifest.Manifest(manifest=None, signer_ca=None)¶
Bases:
object
Container for Microchip manifests.
- append(secure_element)¶
Add a new entry in the Manifest
- Parameters:
secure_element (SignedSecureElement, SecureElement) – Secure element or signed secure element.
- dumps()¶
Serialize the Manifest
- Returns:
Manifest as pretty formatted json.
- Return type:
str
- find_secure_element(identifier)¶
Find secure element in Manifest.
- Parameters:
identifier (str) – Secure element Identifier e.g. for ECC devices the hex encoded serial number in lower case letters.
- Returns:
Signed secure element if sucessfull otherwise None.
- Return type:
SignedSecureElement or None
- class pytrustplatform.manifest.manifest.ManifestSigner(cert=None, key=None)¶
Bases:
object
Manifest signer
The manifest signer is used to verify manifest entries and to sign new entries.
- find_cert(fingerprint, path=VERIFICATION_CERTIFICATES_FOLDER)¶
Find a certificate that matches a fingerprint and load it.
The certificates in the path location must be in PEM format.
- Parameters:
fingerprint (bytes, bytearray) – Certificate fingerprint (SHA256 of a certificate in DER format)
path (str, optional) – Path to check for certificates, defaults to VERIFICATION_CERTIFICATES_FOLDER
- Returns:
Certificate
- Return type:
Certificate
- fingerprint = b''¶
- load(certificate, key=None)¶
Initialize the manifest signer with new certificate and key
- Parameters:
certificate (Certificate) – Manifest signer certificate
key (bytes or bytearray, optional) – Manifest signer key, defaults to None. Not needed when only reading manifests.
- class pytrustplatform.manifest.manifest.SecureElement¶
Bases:
object
Secure Element.
- get_certificate(key_index, cert_index)¶
Get certificate from secure element
- Parameters:
cert_index (int) – Certificate index. If the public key has a certificate associated with it, then that certificate will be found at the first index position. Subsequent certificates in the array will be the CA certificates used to validate the previous one.
key_index (int) – Key the certificate(s) are associated with.
- Returns:
Certificate in BASE64 encoded (not unpdadded BASE64URL, and not PEM) strings of the DER certificate. This is defined in RFC7517 section 4.7.
- Return type:
str
- set_provisioning_time(time)¶
Set the secure element provisioning timestamp.
- Parameters:
time (datetime) – Date and time the secured element was provisioned in UTC. This is usually taken from the device certificate “not valid before” field.
- set_publicJWK(kid, kty='', crv='', x=None, y=None, x5c=None)¶
Add a public JSON Web Key (JWK) element to the secure element.
- Parameters:
kid (str) – Key ID string. This uniquely identifies this key on the secure element. For Crypto Authentication secure elements, this will be the slot number of the corresponding private key.
kty (str, optional) – Key type. Crypto Authentication secure elements only support “EC” public keys as defined in RFC 7518 section 6.1., defaults to ‘’.
crv (str, optional) – For elliptic curve keys, this is the curve name. Crypto Authentication secure elements only support the “P-256” curve as defined in RFC 7518 section 6.2.1.1., defaults to ‘’
x (str, optional) – Unpadded BASE64URL encoded x component of the public key. For elliptic curve keys, this is the encoded public key X integer as defined in RFC 7518 section 6.2.1.2., defaults to None
y (str, optional) – Unpadded BASE64URL encoded x component of the public key. For elliptic curve keys, this is the encoded public key Y integer as defined in RFC 7518 section 6.2.1.3., defaults to None
x5c (str, optional) – If the public key has a certificate associated with it, then that certificate will be found at the first position in this array. Subsequent certificates in the array will be the CA certificates used to validate the previous one. Certificates will be BASE64 encoded (not unpdadded BASE64URL) strings of the DER certificate. This is defined in RFC7517 section 4.7., defaults to None
- set_unique_id(uniqueid)¶
Set the unique identifier for the secure element.
- Parameters:
uniqueid (str, bytes) – Unique identifier for the secure element. For Crypto Authentication devices, this is the 9 byte device serial number or a lower-case hex string.
- class pytrustplatform.manifest.manifest.SignedSecureElement(secure_element, signer_ca=None)¶
Bases:
object
Manifest Signed Secure Element
- encode(secure_element)¶
Build the signed secured element.
- Parameters:
secure_element (SecureElement or instance thereof.) – Secure element to build the signed secured element.
- Returns:
Signed secured element
- Return type:
str
- get_secure_element(se_type=None)¶
Get secure element.
- Parameters:
se_type (SecureElement or any sub-class e.g. TnGoSecureElement, optional) – Secure element type e.g. TnGoTlsSecureElement, defaults to None. If no type is provided the partNumber field in the signed secured element is checked to find a match. If this is unsucessful a generic SecureElement will be returned.
- Returns:
Secure element.
- Return type:
SecureElement or subclass thereof
- verify()¶
Verify the signed secured element.
The function will check if the certificate provided through the class initialization matches the fingerprint of the signed secure element signer. If not, it will check the Microchip manifest signers that are included in this library for a matching fingerprint. If a matching certificate is found its public key is used to verify the signed secured element. If no match is found a ValueError is raised.
- class pytrustplatform.manifest.manifest.TcustomTlsSecureElement¶
Bases:
TnGoTlsSecureElement
Trust and Go Secure Element.
- class pytrustplatform.manifest.manifest.TnFlexTlsSecureElement¶
Bases:
TnGoTlsSecureElement
Trust and Go Secure Element.
- class pytrustplatform.manifest.manifest.TnGoTlsSecureElement¶
Bases:
SecureElement
Trust and Go Secure Element.
- build(data_provider)¶
Build the secure element.
- Parameters:
data_provider (ManifestDataProvider implementation) – Data provider that implements ManifestDataProvider abstract class.
- get_device_certificate()¶
Get the device certificate
- Returns:
Device certificate in BASE64 format.
- Return type:
str
- get_signer_certificate()¶
Get the signer certificate
- Returns:
Signer certificate in BASE64 format.
- Return type:
str
- pytrustplatform.manifest.manifest.load_cert(cert_file_name, encoding='pem')¶
Load certificate from file.
- Parameters:
cert_file_name (str) – File name
encoding (str, optional) – Certificate encoding, either pem or der, defaults to “pem”
- Returns:
Certificate object as defined in cryptography library.
- Return type:
Certificate object
- pytrustplatform.manifest.manifest.urlsafe_b64decode_unpadded(s)¶
Unpadded url-safe base64 decoding
- Parameters:
s (str, bytes) – Base64 encoded data without padding (no “=” padding)
- Returns:
Decoded data
- Return type:
bytes
- pytrustplatform.manifest.manifest.urlsafe_b64encode_unpadded(s)¶
Unpadded url-safe base64 encoding.
- Parameters:
s (bytes) – Data to encode.
- Returns:
Base64 encoded data without padding (no “=” padding)
- Return type:
bytes
Manifest data provider¶
Data providers for manifest building
The abstract class ManifestDataProvider describes an interface that the manifest library uses to obtain secure element data to build a new entry in a manifest.
Implementations of the ManifestDataProvider are e.g. * EccDataProvider: Fetches data from a physical ECC device on supported tools. * CertsData: Extracts data from device and signer certificates. * EccTestData: Dummy test data provider.
- class pytrustplatform.manifest.data_provider.CertsData(device_cert, signer_cert)¶
Bases:
ManifestDataProvider
Data provider for manifest generation based on certificates.
Extracts data from a device and signer certificate and provides this to the manifest builder as input.
- get_certificate(chain_index)¶
Provides the certificates for the manifest generation.
- Parameters:
chain_index (int) – Position of the certificate in the chain e.g. 0=device certificate, 1=signer certificate
- Returns:
BASE64 encoded certificate or None
- Return type:
str
- get_provisioning_time()¶
Provides the provisioning time of the secure element.
- Returns:
Provisioning time is extracted from device certificate not-valid-before field.
- Return type:
datetime
- get_pubkey(index)¶
Provides the public key from the certificate.
- Parameters:
index (int) – Index of the public key. Corresponds to the slot in ATECC608 secure element. Since a certificate only contains the key from slot 0 we will only return a key when the index is 0, otherwise None.
- Returns:
Public key or None. For EC keys raw X and Y coordinates e.g. 64 bytes for P256 curve coordinates (uncompressed format but without first byte).
- Return type:
bytes
- get_serial_number()¶
Provides secure element serial number
- Returns:
Serial number in hex encoded lower case letters.
- Return type:
str
- class pytrustplatform.manifest.data_provider.EccDataProvider(kit_info)¶
Bases:
ManifestDataProvider
Provides secure element data from ECC devices
- get_certificate(chain_index)¶
Provides the certificates for the manifest generation.
- Parameters:
chain_index (int) – Position of the certificate in the chain e.g. 0=device certificate, 1=signer certificate
- Returns:
BASE64 encoded certificate or None
- Return type:
str
- get_provisioning_time()¶
Provides the provisioning time of the secure element.
- Returns:
Provisioning time is extracted from device certificate not-valid-before field.
- Return type:
datetime
- get_pubkey(index)¶
Get public key.
- Parameters:
index (int) – Key index of secure element.
- Returns:
Public key. For EC keys raw X and Y coordinates e.g. 64 bytes for P256 curve coordinates (uncompressed format but without first byte).
- Return type:
bytes
- get_secure_element()¶
Get the secure element
- Returns:
Secure element instance
- Return type:
Subclass of SecureElement e.g. TnGoTlsSecureElement, TnFlexTlsSecureElement …
- get_serial_number()¶
Provides secure element serial number
- Returns:
Serial number in hex encoded lower case letters.
- Return type:
str
- class pytrustplatform.manifest.data_provider.EccTestData¶
Bases:
ManifestDataProvider
Dummy data provider for testing.
- get_certificate(chain_index)¶
Provides the certificates for the manifest generation.
- Parameters:
chain_index (int) – Position of the certificate in the chain e.g. 0=device certificate, 1=signer certificate
- Returns:
BASE64 encoded certificate or None
- Return type:
str
- get_provisioning_time()¶
Get secure element provisioning time.
- Returns:
Provisioning time.
- Return type:
datetime
- get_pubkey(index)¶
Dummy public key.
- Parameters:
slot (int) – Key index.
- Returns:
Public key, 64 bytes.
- Return type:
bytes
- get_secure_element()¶
Get the secure element
- Returns:
Secure element instance
- Return type:
Subclass of SecureElement e.g. TnGoTlsSecureElement, TnFlexTlsSecureElement …
- get_serial_number()¶
Dummy test serial number.
- Returns:
ECC serial number 9 bytes long
- Return type:
bytes
- class pytrustplatform.manifest.data_provider.ManifestDataProvider¶
Bases:
ABC
ECC data provider abstract class.
This class defines an interface that is used by the manifest library to build a SecureElement which then can be added to a manifest. Implementations of this class could be e.g. a dummy data provider for testing, a provider that gets ECC data via the Trust Platfrom development kit, or via any other development board.
- abstract get_certificate(chain_index)¶
Provides the certificates for the manifest generation.
- Parameters:
chain_index (int) – Position of the certificate in the chain e.g. 0=device certificate, 1=signer certificate
- Returns:
BASE64 encoded certificate or None
- Return type:
str
- abstract get_pubkey(index)¶
Get public key.
- Parameters:
index (int) – Key index of secure element.
- Returns:
Public key. For EC keys raw X and Y coordinates e.g. 64 bytes for P256 curve coordinates (uncompressed format but without first byte).
- Return type:
bytes
- abstract get_serial_number()¶
Get the serial number of the crypto device
- Returns:
Serial number.
- Return type:
bytes
Serial number utilities¶
serial number utility functions
- pytrustplatform.serialnumber.new_device_serialnumber(device_serial_number, size=16, not_valid_before=None, not_valid_after=None, enc_dates=None)¶
Creates serial number from SHA256(device SN [9 bytes] + encoded dates [3 bytes])
Takes either not_valid_before and not_valid_after, or raw enc_dates. If both are provided the dates will have preference.
- Parameters:
size (int) – Size of the serial number max 32. 16 is used for ECC608 certificates.
not_valid_before (datetime) – Certificate not valid before date.
not_valid_after (datetime) – Certificate not valid after date.
enc_dates (bytearray) – Encoded dates from compressed certificate (3 bytes)
- pytrustplatform.serialnumber.new_publickey_serialnumber(pubkey, size=16, not_valid_before=None, not_valid_after=None, enc_dates=None)¶
Create serial number from SHA256(Subject public key + Encoded dates)
Takes either not_valid_before and not_valid_after, or raw enc_dates. If both are provided the dates will have preference.
- Parameters:
size (int) – Size of the serial number max 32. 16 is used for ECC608 certificates.
not_valid_before (datetime) – Certificate not valid before date.
not_valid_after (datetime) – Certificate not valid after date.
enc_dates (bytearray) – Encoded dates from compressed certificate (3 bytes)
- pytrustplatform.serialnumber.new_random_serialnumber(size=16)¶
Create a positive, non-trimmable serial number for X.509 certificates
- Parameters:
size (int) – Size of the serial number max 32. 16 is used for ECC608 certificates.
Errors¶
pytrustplatform specific exceptions
- exception pytrustplatform.pytrust_errors.PytrustCertificateError(msg=None, code=0)¶
Bases:
PytrustError
Signals a problem with a certificate
- exception pytrustplatform.pytrust_errors.PytrustError(msg=None, code=0)¶
Bases:
Exception
Base class for all pytrustplatform specific exceptions
pytrustplatform¶
Python Trust Platform utilities¶
pytrustplatform is a collection of utilities for interacting with Microchip Trust Platform and Microchip CryptoAuthentication(TM) devices
Overview¶
- pytrustplatform is available:
install using pip from pypi: https://pypi.org/project/pytrustplatform
browse source code on github: https://github.com/microchip-pic-avr-tools/pytrustplatform
read API documentation on github: https://microchip-pic-avr-tools.github.io/pytrustplatform
read the changelog on github: https://github.com/microchip-pic-avr-tools/pytrustplatform/blob/main/CHANGELOG.md
Fetching data from a certificate¶
The cert_get_data module contains functions to fetch various information from a certificate.
Fetch the Subject Key Identifier from a certificate
from pytrustplatform.cert_get_data import cert_get_skid
skid = cert_get_skid("mycertificate.crt")
Fetch Common Name from a certificate:
from pytrustplatform.cert_get_data import cert_get_common_name
common_name = cert_get_common_name("mycertificate.crt")
Create Fingerprint from a certificate:
from pytrustplatform.cert_get_data import create_cert_fingerprint
fingerprint = create_cert_fingerprint("mycertificate.crt")
Create device certificate and CSR¶
The device_cert_builder module contains functions to create device certificates and Certificate Signing Requests (CSR) for a connected Microchip IoT kit.
# Ask pykitcommander to setup the kit with the appropriate firmware
from pykitcommander.kitprotocols import setup_kit
info = setup_kit('iotprovision')
# Collect required info to continue:
port = info['port']
baud = info['protocol_baud']
protocol = info['protocol_class']
# Build the device certificate. A CSR will be generated as part of the process.
# Both will be written to file. The serial port connection uses pyserial, in a
# context manager to ensure the port is closed after use
from serial import Serial
with Serial(port=port, baudrate=baud) as serial_connection:
firmware_driver = protocol(serial_connection)
from pytrustplatform.device_cert_builder import build_device_cert
device_cert = build_device_cert(firmware_driver,
"my_signer-ca.crt",
"my_signer-ca.key",
"generated.csr",
"generated_device.crt")
Create device and signer certificate from ECC data¶
The ecc_cert_builder module contains functions to create device certificates and signer certificates from data collected from an ECC device of a connected Microchip IoT kit.
# Ask pykitcommander to setup the kit with the appropriate firmware
from pykitcommander.kitprotocols import setup_kit
info = setup_kit('iotprovision')
# Collect required info to continue:
port = info['port']
baud = info['protocol_baud']
protocol = info['protocol_class']
# Build the device certificate and signer certificate. Both will be written to file.
# The serial port connection uses pyserial, in a context manager to ensure the port is
# closed after use
from serial import Serial
with Serial(port=port, baudrate=baud) as serial_connection:
firmware_driver = protocol(serial_connection)
from pytrustplatform.ecc_cert_builder import build_certs_from_ecc
ecc_device_cert, ecc_signer_cert = build_certs_from_ecc(firmware_driver,
"generated_signer.crt",
"generated_device.crt")
Create verification certificate¶
The verification_cert_builder module contains a function to create verification certificates. A verification certificate is typically used when registering a Certificate Authority (CA) with a cloud provider.
Create a verification certificate from a signer CA certificate and private key
from pytrustplatform.verification_cert_builder import build_verification_cert
verification_cert = build_verification_cert("my_signer-ca.crt",
"my_signer-ca.key",
"MY_REGCODE_0123456789",
"generated_verification.crt")
Create chain of trust¶
The ca_create module contains functions to create a chain of trust. Keys can be generated or already existing keys can be provided
from pytrustplatform.ca_create import ca_create_root, ca_create_signer_csr, ca_create_signer
# Create Root, generates root private key (if it does not exist) and root certificate
ca_create_root("generated_root.key", "generated_root.crt")
# Create signer CA CSR and signer CA private key (if it does not exist)
ca_create_signer_csr("generated_signer_ca.key", "generated_signer_ca.csr")
# Create signer certificate based on previously generated root key, root certificate and signer CSR
ca_create_signer("generated_signer_ca.csr",
"generated_signer_ca.crt",
"generated_root.key",
"generated_root.crt")
Logging¶
This package uses the Python logging module for publishing log messages to library users. A basic configuration can be used (see example below), but for best results a more thorough configuration is recommended in order to control the verbosity of output from dependencies in the stack which also use logging. See logging.yaml which is included in the package (although only used for CLI)
Simple logging configuration example:
import logging
logging.basicConfig(format="%(levelname)s: %(message)s", level=logging.WARNING)
Dependencies¶
pytrustplatform depends on pykitcommander to manage Microchip IoT kit firmware and connection. pytrustplatform depends on pyedbglib for its transport protocol. pyedbglib requires a USB transport library like libusb. See pyedbglib package for more information.