Crypto Module API
Crypto Module provides basic key’s and certificate’s operations.
Crypto module general information
Module for crypto operations (certificate and key management).
Crypto module key generation
Module for key generation and saving keys to file.
- class spsdk.crypto.keys.EccCurve(value)
Bases:
str
,enum.Enum
Supported ecc key types.
- SECP256R1 = 'secp256r1'
- SECP384R1 = 'secp384r1'
- SECP521R1 = 'secp521r1'
- class spsdk.crypto.keys.KeyEccCommon
Bases:
object
SPSDK Common Key.
- property coordinate_size: int
Size of signature data.
- Return type
int
- property curve: spsdk.crypto.keys.EccCurve
Curve type.
- Return type
- key: Union[cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey]
- property key_size: int
Key size in bits.
- Return type
int
- static serialize_signature(signature, coordinate_length)
Re-format ECC ANS.1 DER signature into the format used by ROM code.
- Return type
bytes
- property signature_size: int
Size of signature data.
- Return type
int
- class spsdk.crypto.keys.PrivateKey
Bases:
spsdk.utils.abstract.BaseClass
,abc.ABC
SPSDK Private Key.
- classmethod create(key)
Create Private Key object.
- Parameters
key (
Any
) – Supported private key.- Raises
SPSDKInvalidKeyType – Unsupported private key given
- Return type
Self
- Returns
SPSDK Private Kye object
- abstract export(password=None, encoding=SPSDKEncoding.DER)
Export key into bytes in requested format.
- Parameters
password (
Optional
[str
]) – password to private key; None to store without passwordencoding (
SPSDKEncoding
) – encoding type, default is DER
- Return type
bytes
- Returns
Byte representation of key
- abstract classmethod generate_key()
Generate SPSDK Key (private key).
- Return type
Self
- Returns
SPSDK private key
- key: Any
- abstract property key_size: int
Key size in bits.
- Return type
int
- Returns
Key Size
- classmethod load(file_path, password=None)
Load the Private key from the given file.
- Parameters
file_path (
str
) – path to the file, where the key is storedpassword (
Optional
[str
]) – password to private key; None to load without password
- Return type
Self
- classmethod parse(data, password=None)
Deserialize object from bytes array.
- Parameters
data (
bytes
) – Data to be parsedpassword (
Optional
[str
]) – password to private key; None to store without password
- Return type
Self
- Returns
Recreated key
- save(file_path, password=None, encoding=SPSDKEncoding.PEM)
Save the Private key to the given file.
- Parameters
file_path (
str
) – path to the file, where the key will be storedpassword (
Optional
[str
]) – password to private key; None to store without passwordencoding (
SPSDKEncoding
) – encoding type, default is PEM
- Return type
None
- abstract sign(data)
Sign input data.
- Parameters
data (
bytes
) – Input data- Return type
bytes
- Returns
Signed data
- abstract property signature_size: int
Size of signature data.
- Return type
int
- class spsdk.crypto.keys.PrivateKeyEcc(key)
Bases:
spsdk.crypto.keys.KeyEccCommon
,spsdk.crypto.keys.PrivateKey
SPSDK Private Key.
Create SPSDK Ecc Private Key.
- Parameters
key (
EllipticCurvePrivateKey
) – Only Ecc key is accepted
- property d: int
Private number D.
- Return type
int
- exchange(peer_public_key)
Exchange key using ECDH algorithm with provided peer public key.
- Parameters
peer_public_key (
PublicKeyEcc
) – Peer public key- Return type
bytes
- Returns
Shared key
- export(password=None, encoding=SPSDKEncoding.DER)
Export the Private key to the bytes in requested format.
- Parameters
password (
Optional
[str
]) – password to private key; None to store without passwordencoding (
SPSDKEncoding
) – encoding type, default is DER
- Return type
bytes
- Returns
Private key in bytes
- classmethod generate_key(curve_name=EccCurve.SECP256R1)
Generate SPSDK Key (private key).
- Parameters
curve_name (
EccCurve
) – Name of curve- Return type
Self
- Returns
SPSDK private key
- get_public_key()
Generate public key.
- Return type
- Returns
Public key
- key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey
- classmethod parse(data, password=None)
Deserialize object from bytes array.
- Parameters
data (
bytes
) – Data to be parsedpassword (
Optional
[str
]) – password to private key; None to store without password
- Return type
Self
- Returns
Recreated key
- classmethod recreate(d, curve)
Recreate ECC private key from private key number.
- Parameters
d (
int
) – Private number D.curve (
EccCurve
) – ECC curve.
- Return type
Self
- Returns
ECC private key.
- sign(data, algorithm=None, der_format=False, prehashed=False)
Sign input data.
- Parameters
data (
bytes
) – Input dataalgorithm (
Optional
[EnumHashAlgorithm
]) – Used algorithmder_format (
bool
) – Use DER format as a outputprehashed (
bool
) – Use pre hashed value as input
- Return type
bytes
- Returns
Signed data
- class spsdk.crypto.keys.PrivateKeyRsa(key)
Bases:
spsdk.crypto.keys.PrivateKey
SPSDK Private Key.
Create SPSDK Key.
- Parameters
key (
RSAPrivateKey
) – Only RSA key is accepted
- SUPPORTED_KEY_SIZES = [2048, 3072, 4096]
- export(password=None, encoding=SPSDKEncoding.DER)
Export the Private key to the bytes in requested encoding.
- Parameters
password (
Optional
[str
]) – password to private key; None to store without passwordencoding (
SPSDKEncoding
) – encoding type, default is DER
- Return type
bytes
- Returns
Private key in bytes
- classmethod generate_key(key_size=2048, exponent=65537)
Generate SPSDK Key (private key).
- Parameters
key_size (
int
) – key size in bits; must be >= 512exponent (
int
) – public exponent; must be >= 3 and odd
- Return type
Self
- Returns
SPSDK private key
- get_public_key()
Generate public key.
- Return type
- Returns
Public key
- key: cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey
- property key_size: int
Key size in bits.
- Return type
int
- Returns
Key Size
- classmethod parse(data, password=None)
Deserialize object from bytes array.
- Parameters
data (
bytes
) – Data to be parsedpassword (
Optional
[str
]) – password to private key; None to store without password
- Return type
Self
- Returns
Recreated key
- sign(data, algorithm=1)
Sign input data.
- Parameters
data (
bytes
) – Input dataalgorithm (
EnumHashAlgorithm
) – Used algorithm
- Return type
bytes
- Returns
Signed data
- property signature_size: int
Size of signature data.
- Return type
int
- class spsdk.crypto.keys.PrivateKeySM2(key)
Bases:
spsdk.crypto.keys.PrivateKey
SPSDK SM2 Private Key.
Create SPSDK Key.
- Parameters
key (
CryptSM2
) – Only SM2 key is accepted
- export(password=None, encoding=SPSDKEncoding.DER)
Convert key into bytes supported by NXP.
- Return type
bytes
- classmethod generate_key()
Generate SM2 Key (private key).
- Return type
Self
- Returns
SM2 private key
- get_public_key()
Generate public key.
- Return type
- Returns
Public key
- key: gmssl.sm2.CryptSM2
- property key_size: int
Size of the key in bits.
- Return type
int
- sign(data, salt=None, use_ber=False)
Sign data using SM2 algorithm with SM3 hash.
- Parameters
data (
bytes
) – Data to sign.salt (
Optional
[str
]) – Salt for signature generation, defaults to None. If not specified a random string will be used.use_ber (
bool
) – Encode signature into BER format, defaults to True
- Raises
SPSDKError – Signature can’t be created.
- Return type
bytes
- Returns
SM2 signature.
- property signature_size: int
Signature size.
- Return type
int
- class spsdk.crypto.keys.PublicKey
Bases:
spsdk.utils.abstract.BaseClass
,abc.ABC
SPSDK Public Key.
- classmethod create(key)
Create Public Key object.
- Parameters
key (
Any
) – Supported public key.- Raises
SPSDKInvalidKeyType – Unsupported public key given
- Return type
Self
- Returns
SPSDK Public Kye object
- abstract export(encoding=SPSDKEncoding.NXP)
Export key into bytes to requested format.
- Parameters
encoding (
SPSDKEncoding
) – encoding type, default is NXP- Return type
bytes
- Returns
Byte representation of key
- key: Any
- key_hash(algorithm=1)
Get key hash.
- Parameters
algorithm (
EnumHashAlgorithm
) – Used hash algorithm, defaults to sha256- Return type
bytes
- Returns
Key Hash
- classmethod load(file_path)
Load the Public key from the given file.
- Parameters
file_path (
str
) – path to the file, where the key is stored- Return type
Self
- classmethod parse(data)
Deserialize object from bytes array.
- Parameters
data (
bytes
) – Data to be parsed- Return type
Self
- Returns
Recreated key
- abstract property public_numbers: Any
Public numbers.
- Return type
Any
- save(file_path, encoding=SPSDKEncoding.PEM)
Save the public key to the file.
- Parameters
file_path (
str
) – path to the file, where the key will be storedencoding (
SPSDKEncoding
) – encoding type, default is PEM
- Return type
None
- abstract property signature_size: int
Size of signature data.
- Return type
int
- abstract verify_signature(signature, data, algorithm=1)
Verify input data.
- Parameters
signature (
bytes
) – The signature of input datadata (
bytes
) – Input dataalgorithm (
EnumHashAlgorithm
) – Used algorithm
- Return type
bool
- Returns
True if signature is valid, False otherwise
- class spsdk.crypto.keys.PublicKeyEcc(key)
Bases:
spsdk.crypto.keys.KeyEccCommon
,spsdk.crypto.keys.PublicKey
SPSDK Public Key.
Create SPSDK Public Key.
- Parameters
key (
EllipticCurvePublicKey
) – SPSDK Public Key data or file path
- export(encoding=SPSDKEncoding.NXP)
Export the public key to the bytes in requested format.
- Parameters
encoding (
SPSDKEncoding
) – encoding type, default is NXP- Return type
bytes
- Returns
Public key in bytes
- key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey
- classmethod parse(data)
Deserialize object from bytes array.
- Parameters
data (
bytes
) – Data to be parsed- Return type
Self
- Returns
Recreated key
- property public_numbers: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers
Public numbers of key.
- Return type
EllipticCurvePublicNumbers
- Returns
Public numbers
- classmethod recreate(coor_x, coor_y, curve)
Recreate ECC public key from coordinates.
- Parameters
coor_x (
int
) – X coordinate of point on curve.coor_y (
int
) – Y coordinate of point on curve.curve (
EccCurve
) – ECC curve.
- Return type
Self
- Returns
ECC public key.
- classmethod recreate_from_data(data, curve=None)
Recreate ECC public key from coordinates in data blob.
- Parameters
data (
bytes
) – Data blob of coordinates in bytes (X,Y in Big Endian)curve (
Optional
[EccCurve
]) – ECC curve.
- Return type
Self
- Returns
ECC public key.
- verify_signature(signature, data, algorithm=None, prehashed=False)
Verify input data.
- Parameters
signature (
bytes
) – The signature of input datadata (
bytes
) – Input dataalgorithm (
Optional
[EnumHashAlgorithm
]) – Used algorithmprehashed (
bool
) – Use pre hashed value as input
- Return type
bool
- Returns
True if signature is valid, False otherwise
- property x: int
Public number X.
- Return type
int
- Returns
X
- property y: int
Public number Y.
- Return type
int
- Returns
Y
- class spsdk.crypto.keys.PublicKeyRsa(key)
Bases:
spsdk.crypto.keys.PublicKey
SPSDK Public Key.
Create SPSDK Public Key.
- Parameters
key (
RSAPublicKey
) – SPSDK Public Key data or file path
- property e: int
Public number E.
- Return type
int
- Returns
E
- export(encoding=SPSDKEncoding.NXP, exp_length=None, modulus_length=None)
Save the public key to the bytes in NXP or DER format.
- Parameters
encoding (
SPSDKEncoding
) – encoding type, default is NXPexp_length (
Optional
[int
]) – Optional specific exponent length in bytesmodulus_length (
Optional
[int
]) – Optional specific modulus length in bytes
- Return type
bytes
- Returns
Public key in bytes
- key: cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey
- property key_size: int
Key size in bits.
- Return type
int
- Returns
Key Size
- property n: int
Public number N.
- Return type
int
- Returns
N
- classmethod parse(data)
Deserialize object from bytes array.
- Parameters
data (
bytes
) – Data to be parsed- Return type
Self
- Returns
Recreated key
- property public_numbers: cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicNumbers
Public numbers of key.
- Return type
RSAPublicNumbers
- Returns
Public numbers
- classmethod recreate(exponent, modulus)
Recreate RSA public key from Exponent and modulus.
- Parameters
exponent (
int
) – Exponent of RSA key.modulus (
int
) – Modulus of RSA key.
- Return type
Self
- Returns
RSA public key.
- static recreate_public_numbers(data)
Recreate public numbers from data.
- Parameters
data (
bytes
) – Dat with raw key.- Raises
SPSDKError – Un recognized data.
- Return type
RSAPublicNumbers
- Returns
RAS public numbers.
- property signature_size: int
Size of signature data.
- Return type
int
- verify_signature(signature, data, algorithm=1)
Verify input data.
- Parameters
signature (
bytes
) – The signature of input datadata (
bytes
) – Input dataalgorithm (
EnumHashAlgorithm
) – Used algorithm
- Return type
bool
- Returns
True if signature is valid, False otherwise
- class spsdk.crypto.keys.PublicKeySM2(key)
Bases:
spsdk.crypto.keys.PublicKey
SM2 Public Key.
Create SPSDK Public Key.
- Parameters
key (
CryptSM2
) – SPSDK Public Key data or file path
- export(encoding=SPSDKEncoding.DER)
Convert key into bytes supported by NXP.
- Return type
bytes
- Returns
Byte representation of key
- key: gmssl.sm2.CryptSM2
- property public_numbers: str
Public numbers of key.
- Return type
str
- Returns
Public numbers
- classmethod recreate(data)
Recreate SM2 public key from data.
- Parameters
data (
bytes
) – public key data- Return type
Self
- Returns
SPSDK public key.
- classmethod recreate_from_data(data)
Recreate SM2 public key from data.
- Parameters
data (
bytes
) – PEM or DER encoded key.- Return type
Self
- Returns
SM2 public key.
- property signature_size: int
Signature size.
- Return type
int
- verify_signature(signature, data, algorithm=None)
Verify signature.
- Parameters
signature (
bytes
) – SM2 signature to verifydata (
bytes
) – Signed dataalgorithm (
Optional
[EnumHashAlgorithm
]) – Just to keep compatibility with abstract class
- Raises
SPSDKError – Invalid signature
- Return type
bool
- exception spsdk.crypto.keys.SPSDKInvalidKeyType(desc=None)
Bases:
spsdk.exceptions.SPSDKError
Invalid Key Type.
Initialize the base SPSDK Exception.
- exception spsdk.crypto.keys.SPSDKKeyPassphraseMissing(desc=None)
Bases:
spsdk.exceptions.SPSDKError
Passphrase for decryption of private key is missing.
Initialize the base SPSDK Exception.
- exception spsdk.crypto.keys.SPSDKUnsupportedEccCurve(desc=None)
Bases:
spsdk.exceptions.SPSDKValueError
Unsupported Ecc curve error.
Initialize the base SPSDK Exception.
- spsdk.crypto.keys.get_ecc_curve(key_length)
Get curve name for Crypto library.
- Parameters
key_length (
int
) – Length of ecc key in bytes- Return type
- spsdk.crypto.keys.get_supported_keys_generators()
Generate list with list of supported key types.
- Return type
Dict
[str
,Tuple
[Callable
[...
,PrivateKey
],Dict
[str
,Union
[int
,str
,bool
]]]]- Returns
KeyGeneratorInfo dictionary of supported key types.
Crypto module certificate generation
Module for certificate management (generating certificate, validating certificate, chains).
- class spsdk.crypto.certificate.Certificate(certificate)
Bases:
spsdk.utils.abstract.BaseClass
SPSDK Certificate representation.
Constructor of SPSDK Certificate.
- Parameters
certificate (
Certificate
) – Cryptography Certificate representation.
- property ca: bool
Check if CA flag is set in certificate.
- Return type
bool
- Returns
true/false depending whether ca flag is set or not
- export(encoding=SPSDKEncoding.NXP)
Convert certificates into bytes.
- Parameters
encoding (
SPSDKEncoding
) – encoding type- Return type
bytes
- Returns
certificate in bytes form
- property extensions: cryptography.x509.extensions.Extensions
Returns an Extensions object.
- Return type
Extensions
- static generate_certificate(subject, issuer, subject_public_key, issuer_private_key, serial_number=None, if_ca=True, duration=3650, path_length=2)
Generate certificate.
- Parameters
subject (
Name
) – subject name that the CA issues the certificate toissuer (
Name
) – issuer name that issued the certificatesubject_public_key (
PublicKey
) – Public key of subjectissuer_private_key (
PrivateKey
) – Private key of issuerserial_number (
Optional
[int
]) – certificate serial number, if not specified, random serial number will be setif_ca (
bool
) – true if the certificate can sign certificates, none otherwiseduration (
int
) – how long the certificate will be valid (in days)path_length (
int
) – The maximum path length for certificates subordinate to this certificate.
- Return type
- Returns
certificate
- property issuer: cryptography.x509.name.Name
Returns the issuer name object.
- Return type
Name
- classmethod load(file_path)
Load the Certificate from the given file.
- Parameters
file_path (
str
) – path to the file, where the key is stored- Return type
Self
- classmethod parse(data)
Deserialize object from bytes array.
- Parameters
data (
bytes
) – Data to be parsed- Return type
Self
- Returns
Recreated certificate
- public_key_hash(algorithm=1)
Get key hash.
- Parameters
algorithm (
EnumHashAlgorithm
) – Used hash algorithm, defaults to sha256- Return type
bytes
- Returns
Key Hash
- property raw_size: int
Raw size of the certificate.
- Return type
int
- save(file_path, encoding_type=SPSDKEncoding.PEM)
Save the certificate/CSR into file.
- Parameters
file_path (
str
) – path to the file where item will be storedencoding_type (
SPSDKEncoding
) – encoding type (PEM or DER)
- Return type
None
- property self_signed: bool
Indication whether the Certificate is self-signed.
- Return type
bool
- property serial_number: int
Returns certificate serial number.
- Return type
int
- property signature: bytes
Returns the signature bytes.
- Return type
bytes
- property signature_algorithm_oid: cryptography.hazmat.bindings._rust.ObjectIdentifier
Returns the ObjectIdentifier of the signature algorithm.
- Return type
ObjectIdentifier
- property signature_hash_algorithm: Optional[cryptography.hazmat.primitives.hashes.HashAlgorithm]
Returns a HashAlgorithm corresponding to the type of the digest signed in the certificate.
- Return type
Optional
[HashAlgorithm
]
- property subject: cryptography.x509.name.Name
Returns the subject name object.
- Return type
Name
- property tbs_certificate_bytes: bytes
Returns the tbsCertificate payload bytes as defined in RFC 5280.
- Return type
bytes
- validate(issuer_certificate)
Validate certificate.
- Parameters
issuer_certificate (
Certificate
) – Issuer’s certificate- Raises
SPSDKError – Unsupported key type in Certificate
- Return type
bool
- Returns
true/false whether certificate is valid or not
- validate_subject(subject_certificate)
Validate certificate.
- Parameters
subject_certificate (
Certificate
) – Subject’s certificate- Raises
SPSDKError – Unsupported key type in Certificate
- Return type
bool
- Returns
true/false whether certificate is valid or not
- property version: cryptography.x509.base.Version
Returns the certificate version.
- Return type
Version
- exception spsdk.crypto.certificate.SPSDKExtensionNotFoundError(desc=None)
Bases:
spsdk.exceptions.SPSDKError
,cryptography.x509.extensions.ExtensionNotFound
Extension not found error.
Initialize the base SPSDK Exception.
- spsdk.crypto.certificate.generate_name(config)
Generate x509 Name.
- Parameters
config (
Union
[List
[Dict
[str
,str
]],Dict
[str
,Union
[str
,List
[str
]]]]) – subject/issuer description- Return type
Name
- Returns
x509.Name
- spsdk.crypto.certificate.validate_ca_flag_in_cert_chain(chain_list)
Validate CA flag in certification chain.
- Parameters
chain_list (
List
[Certificate
]) – list of certificates in the chain- Return type
bool
- Returns
true/false depending whether ca flag is set or not
- spsdk.crypto.certificate.validate_certificate_chain(chain_list)
Validate chain of certificates.
- Parameters
chain_list (
List
[Certificate
]) – list of certificates in chain- Return type
List
[bool
]- Returns
list of boolean values, which corresponds to the certificate validation in chain
- Raises
SPSDKError – When chain has less than two certificates
Crypto module symmetric encryption/decryption
OpenSSL implementation for symmetric key encryption.
- class spsdk.crypto.symmetric.Counter(nonce, ctr_value=None, ctr_byteorder_encoding='little')
Bases:
object
AES counter with specified counter byte ordering and customizable increment.
Constructor.
- Parameters
nonce (
bytes
) – last four bytes are used as initial value for counterctr_value (
Optional
[int
]) – counter initial value; it is added to counter value retrieved from noncectr_byteorder_encoding (
str
) – way how the counter is encoded into output value: either ‘little’ or ‘big’
- Raises
SPSDKError – When invalid byteorder is provided
- increment(value=1)
Increment counter by specified value.
- Parameters
value (
int
) – to add to counter- Return type
None
- property value: bytes
Initial vector for AES encryption.
- Return type
bytes
- spsdk.crypto.symmetric.aes_cbc_decrypt(key, encrypted_data, iv_data=None)
Decrypt encrypted data with AES in CBC mode.
- Parameters
key (
bytes
) – The key for data decryptionencrypted_data (
bytes
) – Input dataiv_data (
Optional
[bytes
]) – Initialization vector data
- Raises
SPSDKError – Invalid Key or IV
- Return type
bytes
- Returns
Decrypted image
- spsdk.crypto.symmetric.aes_cbc_encrypt(key, plain_data, iv_data=None)
Encrypt plain data with AES in CBC mode.
- Parameters
key (
bytes
) – The key for data encryptionplain_data (
bytes
) – Input dataiv_data (
Optional
[bytes
]) – Initialization vector data
- Raises
SPSDKError – Invalid Key or IV
- Return type
bytes
- Returns
Encrypted image
- spsdk.crypto.symmetric.aes_ccm_decrypt(key, encrypted_data, nonce, associated_data, tag_len=16)
Decrypt encrypted data with AES in CCM mode (Counter with CBC).
- Parameters
key (
bytes
) – The key for data decryptionencrypted_data (
bytes
) – Input datanonce (
bytes
) – Nonce data with counter valueassociated_data (
bytes
) – Associated data - Unencrypted but authenticatedtag_len (
int
) – Length of encryption tag
- Return type
bytes
- Returns
Decrypted data
- spsdk.crypto.symmetric.aes_ccm_encrypt(key, plain_data, nonce, associated_data=b'', tag_len=16)
Encrypt plain data with AES in CCM mode (Counter with CBC).
- Parameters
key (
bytes
) – The key for data encryptionplain_data (
bytes
) – Input datanonce (
bytes
) – Nonce data with counter valueassociated_data (
bytes
) – Associated data - Unencrypted but authenticatedtag_len (
int
) – Length of encryption tag
- Return type
bytes
- Returns
Encrypted data
- spsdk.crypto.symmetric.aes_ctr_decrypt(key, encrypted_data, nonce)
Decrypt encrypted data with AES in CTR mode.
- Parameters
key (
bytes
) – The key for data decryptionencrypted_data (
bytes
) – Input datanonce (
bytes
) – Nonce data with counter value
- Return type
bytes
- Returns
Decrypted data
- spsdk.crypto.symmetric.aes_ctr_encrypt(key, plain_data, nonce)
Encrypt plain data with AES in CTR mode.
- Parameters
key (
bytes
) – The key for data encryptionplain_data (
bytes
) – Input datanonce (
bytes
) – Nonce data with counter value
- Return type
bytes
- Returns
Encrypted data
- spsdk.crypto.symmetric.aes_ecb_decrypt(key, encrypted_data)
Decrypt encrypted data with AES in ECB mode.
- Parameters
key (
bytes
) – The key for data decryptionencrypted_data (
bytes
) – Input data
- Return type
bytes
- Returns
Decrypted data
- spsdk.crypto.symmetric.aes_ecb_encrypt(key, plain_data)
Encrypt plain data with AES in ECB mode.
- Parameters
key (
bytes
) – The key for data encryptionplain_data (
bytes
) – Input data
- Return type
bytes
- Returns
Encrypted data
- spsdk.crypto.symmetric.aes_key_unwrap(kek, wrapped_key)
Unwraps a key using a key-encrypting key (KEK).
- Parameters
kek (
bytes
) – The key-encrypting keywrapped_key (
bytes
) – Encrypted data
- Return type
bytes
- Returns
Un-wrapped key
- spsdk.crypto.symmetric.aes_key_wrap(kek, key_to_wrap)
Wraps a key using a key-encrypting key (KEK).
- Parameters
kek (
bytes
) – The key-encrypting keykey_to_wrap (
bytes
) – Plain data
- Return type
bytes
- Returns
Wrapped key
- spsdk.crypto.symmetric.aes_xts_decrypt(key, encrypted_data, tweak)
Decrypt encrypted data with AES in XTS mode.
- Parameters
key (
bytes
) – The key for data decryptionencrypted_data (
bytes
) – Input datatweak (
bytes
) – The tweak is a 16 byte value
- Return type
bytes
- Returns
Decrypted data
- spsdk.crypto.symmetric.aes_xts_encrypt(key, plain_data, tweak)
Encrypt plain data with AES in XTS mode.
- Parameters
key (
bytes
) – The key for data encryptionplain_data (
bytes
) – Input datatweak (
bytes
) – The tweak is a 16 byte value
- Return type
bytes
- Returns
Encrypted data
- spsdk.crypto.symmetric.sm4_cbc_decrypt(key, encrypted_data, iv_data=None)
Decrypt encrypted data with SM4 in CBC mode.
- Parameters
key (
bytes
) – The key for data decryptionencrypted_data (
bytes
) – Input dataiv_data (
Optional
[bytes
]) – Initialization vector data
- Raises
SPSDKError – Invalid Key or IV
- Return type
bytes
- Returns
Decrypted image
- spsdk.crypto.symmetric.sm4_cbc_encrypt(key, plain_data, iv_data=None)
Encrypt plain data with SM4 in CBC mode.
- Parameters
key (
bytes
) – The key for data encryptionplain_data (
bytes
) – Input dataiv_data (
Optional
[bytes
]) – Initialization vector data
- Raises
SPSDKError – Invalid Key or IV
- Return type
bytes
- Returns
Encrypted image
Crypto module CMS
ASN1Crypto implementation for CMS signature container.
- spsdk.crypto.cms.cms_sign(zulu, data, certificate, signing_key)
Sign provided data and return CMS signature.
- Parameters
zulu (
datetime
) – current UTC time+datedata (
bytes
) – to be signedcertificate (
Certificate
) – Certificate with issuer informationsigning_key (
PrivateKey
) – Signing key
- Return type
bytes
- Returns
CMS signature (binary)
- Raises
SPSDKError – If certificate is not present
SPSDKError – If private key is not present
SPSDKError – If incorrect time-zone”
Crypto module CMAC
OpenSSL implementation for CMAC packet authentication.
- spsdk.crypto.cmac.cmac(key, data)
Return a CMAC from data with specified key and algorithm.
- Parameters
key (
bytes
) – The key in bytes formatdata (
bytes
) – Input data in bytes format
- Return type
bytes
- Returns
CMAC bytes
- spsdk.crypto.cmac.cmac_validate(key, data, signature)
Return a CMAC from data with specified key and algorithm.
- Parameters
key (
bytes
) – The key in bytes formatdata (
bytes
) – Input data in bytes formatsignature (
bytes
) – CMAC signature to validate
- Return type
bool
- Returns
CMAC bytes
Crypto module HMAC
OpenSSL implementation for HMAC packet authentication.
- spsdk.crypto.hmac.hmac(key, data, algorithm=1)
Return a HMAC from data with specified key and algorithm.
- Parameters
key (
bytes
) – The key in bytes formatdata (
bytes
) – Input data in bytes formatalgorithm (
EnumHashAlgorithm
) – Algorithm type for HASH function (sha256, sha384, sha512, …)
- Return type
bytes
- Returns
HMAC bytes
- spsdk.crypto.hmac.hmac_validate(key, data, signature, algorithm=1)
Return a HMAC from data with specified key and algorithm.
- Parameters
key (
bytes
) – The key in bytes formatdata (
bytes
) – Input data in bytes formatsignature (
bytes
) – HMAC signature to validatealgorithm (
EnumHashAlgorithm
) – Algorithm type for HASH function (sha256, sha384, sha512, …)
- Return type
bool
- Returns
HMAC bytes
Crypto module hash
OpenSSL implementation Hash algorithms.
- class spsdk.crypto.hash.EnumHashAlgorithm
Bases:
spsdk.utils.easy_enum.Enum
Hash algorithm enum.
- MD5 = 4
- SHA1 = 0
- SHA256 = 1
- SHA384 = 2
- SHA512 = 3
- SM3 = 5
- spsdk.crypto.hash.get_hash(data, algorithm=1)
Return a HASH from input data with specified algorithm.
- Parameters
data (
bytes
) – Input data in bytesalgorithm (
EnumHashAlgorithm
) – Algorithm type enum
- Return type
bytes
- Returns
Hash-ed bytes
- Raises
SPSDKError – If algorithm not found
- spsdk.crypto.hash.get_hash_algorithm(algorithm)
For specified name return hashes algorithm instance.
- Parameters
algorithm (
EnumHashAlgorithm
) – Algorithm type enum- Return type
HashAlgorithm
- Returns
instance of algorithm class
- Raises
SPSDKError – If algorithm not found
- spsdk.crypto.hash.get_hash_length(algorithm)
For specified name return hash binary length.
- Parameters
algorithm (
EnumHashAlgorithm
) – Algorithm type enum- Return type
int
- Returns
Hash length
- Raises
SPSDKError – If algorithm not found
Crypto module utils
OpenSSL implementation for security backend.
- spsdk.crypto.utils.extract_public_key(file_path, password=None, search_paths=None)
Extract any kind of public key from a file that contains Certificate, Private Key or Public Key.
- Parameters
file_path (
str
) – File path to public key file.password (
Optional
[str
]) – Optional password for encrypted Private file source.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises
SPSDKError – Raised when file can not be loaded
- Return type
- Returns
Public key of any type
- spsdk.crypto.utils.extract_public_key_from_data(object_data, password=None)
Extract any kind of public key from a data that contains Certificate, Private Key or Public Key.
- Raises
SPSDKError – Raised when file can not be loaded
- Return type
- Returns
private key of any type
- spsdk.crypto.utils.extract_public_keys(secret_files, password=None, search_paths=None)
Extract any kind of public key from files that contain Certificate, Private Key or Public Key.
- Parameters
secret_files (
Iterable
[str
]) – List of file paths to public key files.password (
Optional
[str
]) – Optional password for encrypted Private file source.search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Return type
List
[PublicKey
]- Returns
List of public keys of any type
- spsdk.crypto.utils.get_matching_key_id(public_keys, signature_provider)
Get index of public key that match to given private key.
- Parameters
public_keys (
List
[PublicKey
]) – List of public key used to find the match for the private key.signature_provider (
SignatureProvider
) – Signature provider used to try to match public key index.
- Raises
SPSDKValueError – No match found.
- Return type
int
- Returns
Index of public key.
Interface for all potential signature providers
SignatureProvider is an Interface for all potential signature providers.
Each concrete signature provider needs to implement: - sign(data: bytes) -> bytes - signature_length -> int - into() -> str
- class spsdk.crypto.signature_provider.InteractivePlainFileSP(file_path, hash_alg=None, search_paths=None)
Bases:
spsdk.crypto.signature_provider.PlainFileSP
SignatureProvider implementation that uses plain local file in an “interactive” mode.
If the private key is encrypted, the user will be prompted for password
Initialize the interactive plain file signature provider.
- Parameters
file_path (
str
) – Path to private filehash_alg (
Optional
[EnumHashAlgorithm
]) – Hash for the signature, defaults to sha256search_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises
SPSDKError – Invalid Private Key
- sp_type = 'interactive_file'
- class spsdk.crypto.signature_provider.PlainFileSP(file_path, password=None, hash_alg=None, search_paths=None)
Bases:
spsdk.crypto.signature_provider.SignatureProvider
PlainFileSP is a SignatureProvider implementation that uses plain local files.
Initialize the plain file signature provider.
- Parameters
file_path (
str
) – Path to private filepassword (
Optional
[str
]) – Password in case of encrypted private file, defaults to Nonehash_alg (
Optional
[EnumHashAlgorithm
]) – Hash for the signature, defaults to Nonesearch_paths (
Optional
[List
[str
]]) – List of paths where to search for the file, defaults to None
- Raises
SPSDKError – Invalid Private Key
- info()
Return basic into about the signature provider.
- Return type
str
- sign(data)
Return the signature for data.
- Return type
bytes
- property signature_length: int
Return length of the signature.
- Return type
int
- sp_type = 'file'
- verify_public_key(public_key)
Verify if given public key matches private key.
- Return type
bool
- class spsdk.crypto.signature_provider.SignatureProvider
Bases:
abc.ABC
Abstract class (Interface) for all signature providers.
- static convert_params(params)
Coverts creation params from string into dictionary.
e.g.: “type=file;file_path=some_path” -> {‘type’: ‘file’, ‘file_path’: ‘some_path’}
- Return type
Dict
[str
,str
]
- classmethod create(params)
Creates an concrete instance of signature provider.
- Return type
Optional
[SignatureProvider
]
- static get_all_signature_providers()
Get list of all available signature providers.
- Return type
List
[Type
[SignatureProvider
]]
- classmethod get_types()
Returns a list of all available signature provider types.
- Return type
List
[str
]
- info()
Provide information about the Signature provider.
- Return type
str
- abstract sign(data)
Return signature for data.
- Return type
bytes
- abstract property signature_length: int
Return length of the signature.
- Return type
int
- sp_type = 'INVALID'
- verify_public_key(public_key)
Verify if given public key matches private key.
- Return type
bool
Crypto module OSCCA
Support for OSCCA SM2/SM3.
- spsdk.crypto.oscca.SM2Encoder(*args, **kwargs)
- Return type
TypeVar
(_T
)
- class spsdk.crypto.oscca.SM2KeySet(private: str, public: Optional[str])
Bases:
tuple
Bare-bone representation of a SM2 Key.
Create new instance of SM2KeySet(private, public)
- private: str
Alias for field number 0
- public: Optional[str]
Alias for field number 1
- class spsdk.crypto.oscca.SM2PublicKey(public: str)
Bases:
tuple
Bare-bone representation of a SM2 Public Key.
Create new instance of SM2PublicKey(public,)
- public: str
Alias for field number 0
- spsdk.crypto.oscca.sanitize_pem(data)
Covert PEM data into DER.
- Return type
bytes
- spsdk.crypto.oscca.singleton(class_)
Decorator providing Singleton functionality for classes.
- Return type
Type
[TypeVar
(_T
)]
Crypto module types
Based crypto classes.
- class spsdk.crypto.types.SPSDKEncoding(value)
Bases:
cryptography.utils.Enum
Extension of cryptography Encoders class.
- DER = 'DER'
- NXP = 'NXP'
- PEM = 'PEM'
- static all()
Get all supported encodings.
- Return type
Dict
[str
,SPSDKEncoding
]
- static get_cryptography_encodings(encoding)
Get Encoding in cryptography class.
- Return type
Encoding
- static get_file_encodings(data)
Get the encoding type out of given item from the data.
- Parameters
data (
bytes
) – Already loaded data file to determine the encoding style- Return type
- Returns
encoding type (Encoding.PEM, Encoding.DER)
Crypto module RNG
Implementation for getting random numbers.
- spsdk.crypto.rng.rand_below(upper_bound)
Return a random number in range [0, upper_bound].
- Parameters
upper_bound (
int
) – Upper bound- Return type
int
- Returns
Random number
- spsdk.crypto.rng.random_bytes(length)
Return a random byte string with specified length.
- Parameters
length (
int
) – The length in bytes- Return type
bytes
- Returns
Random bytes
- spsdk.crypto.rng.random_hex(length)
Return a random hex string with specified length.
- Parameters
length (
int
) – The length in bytes- Return type
str
- Returns
Random hex