Crypto Module API#
SPSDK cryptographic operations module.
This module provides comprehensive cryptographic functionality including certificate management, key handling, and cryptographic operations for secure provisioning across NXP MCU portfolio.
Crypto module key generation#
SPSDK cryptographic key management and operations.
This module provides comprehensive functionality for handling cryptographic keys including RSA and ECC key types. It supports key generation, loading, saving, and cryptographic operations like signing and verification across the SPSDK ecosystem.
- class spsdk.crypto.keys.ECDSASignature(r, s, ecc_curve)#
Bases:
objectECDSA Signature representation and manipulation.
This class provides functionality for handling ECDSA signatures including parsing from different formats (DER, NXP), exporting to various encodings, and managing signature components (r, s values) along with their associated ECC curve parameters.
- Variables:
COORDINATE_LENGTHS – Mapping of ECC curves to their coordinate byte lengths.
Initialize ECDSA signature with r and s values.
Creates an ECDSA signature object containing the mathematical components of the signature along with the associated elliptic curve parameters.
- Parameters:
r (
int) – The r component of the ECDSA signature (x-coordinate of random point).s (
int) – The s component of the ECDSA signature (calculated signature value).ecc_curve (
EccCurve) – The elliptic curve used for the signature generation.
- COORDINATE_LENGTHS = {EccCurve.SECP256R1: 32, EccCurve.SECP384R1: 48, EccCurve.SECP521R1: 66}#
- export(encoding=<SPSDKEncoding.NXP: 'NXP'>)#
Export signature in DER or NXP format.
The method converts the signature’s r and s coordinates into the specified encoding format. For NXP encoding, it concatenates the r and s values as big-endian bytes. For DER encoding, it uses the standard ASN.1 DER format for DSS signatures.
- Parameters:
encoding (
SPSDKEncoding) – Signature encoding format (NXP or DER).- Raises:
SPSDKValueError – Invalid signature encoding format.
- Return type:
bytes- Returns:
Signature as bytes in the specified encoding format.
- classmethod get_ecc_curve(signature_length)#
Get the Elliptic Curve based on signature length.
The method determines the appropriate ECC curve by matching the signature length against known coordinate lengths. It supports both exact matches and ranges for DER-encoded signatures.
- Parameters:
signature_length (
int) – Length of the signature in bytes- Return type:
- Returns:
The corresponding ECC curve
- Raises:
SPSDKValueError – If signature length doesn’t match any known ECC curve
- classmethod get_encoding(signature)#
Get encoding of signature.
Detects the encoding format of a given signature by analyzing its length and structure. The method first checks for NXP format based on signature length, then attempts to decode as DER format.
- Parameters:
signature (
bytes) – The signature bytes to analyze for encoding detection.- Raises:
SPSDKValueError – When signature doesn’t match any supported encoding format.
- Return type:
- Returns:
The detected encoding format (NXP or DER).
- classmethod parse(signature)#
Parse signature in DER or NXP format.
The method automatically detects the encoding format and creates an instance with the parsed signature components (r, s) and the appropriate ECC curve.
- Parameters:
signature (
bytes) – Binary signature data in either DER or NXP format.- Raises:
SPSDKValueError – Invalid signature encoding format.
- Return type:
Self- Returns:
New instance with parsed signature components.
- class spsdk.crypto.keys.EccCurve(value)#
Bases:
str,EnumEnumeration of supported elliptic curve cryptographic key types.
This enumeration defines the elliptic curve types that are supported by SPSDK cryptographic operations for ECC key generation and processing.
- SECP256R1 = 'secp256r1'#
- SECP384R1 = 'secp384r1'#
- SECP521R1 = 'secp521r1'#
- class spsdk.crypto.keys.KeyEccCommon#
Bases:
objectSPSDK Common ECC Key Handler.
This class provides common functionality for Elliptic Curve Cryptography (ECC) keys, supporting both private and public key operations. It offers standardized access to key properties, signature operations, and curve management across different ECC curve types used in SPSDK cryptographic operations.
- property coordinate_size: int#
Get the coordinate size in bytes.
The coordinate size is calculated based on the key size, representing the number of bytes needed to store one coordinate of the key.
- Returns:
Size of coordinate in bytes.
- property curve: EccCurve#
Get the elliptic curve type of the key.
- Returns:
The elliptic curve type used by this key.
- property default_hash_algorithm: EnumHashAlgorithm#
Get default hash algorithm for signing/verifying operations.
Determines the appropriate hash algorithm based on the key size of the cryptographic key. The mapping follows standard practices: 256-bit keys use SHA256, 384-bit keys use SHA384, and 521-bit keys use SHA512.
- Returns:
Hash algorithm enum value corresponding to the key size.
- Raises:
KeyError – If the key size is not supported (not 256, 384, or 521 bits).
-
key:
Union[EllipticCurvePrivateKey,EllipticCurvePublicKey]#
- property key_size: int#
Get the key size in bits.
- Returns:
Size of the key in bits.
- static serialize_signature(signature, coordinate_length)#
Re-format ECC ANS.1 DER signature into the format used by ROM code.
Converts an ASN.1 DER encoded ECDSA signature into a concatenated format where the r and s coordinates are represented as fixed-length byte arrays.
- Parameters:
signature (
bytes) – ASN.1 DER encoded ECDSA signature bytes.coordinate_length (
int) – Length in bytes for each coordinate (r and s).
- Return type:
bytes- Returns:
Concatenated r and s coordinates as fixed-length byte arrays.
- property signature_size: int#
Get the size of signature data in bytes.
- Returns:
Size of signature data, calculated as coordinate size multiplied by 2.
- class spsdk.crypto.keys.NonSupportingPrivateKey#
Bases:
PrivateKeyPlaceholder class for unsupported private key types.
This class serves as a fallback implementation that raises an exception when instantiated, indicating that the specific private key type is not supported by the SPSDK crypto module.
Initialize unsupported key type constructor.
This constructor is designed to immediately raise an exception to indicate that the specific key type is not supported or implemented in the current version of SPSDK.
- Raises:
SPSDKNotImplementedError – The key type is not supported or implemented.
- class spsdk.crypto.keys.NonSupportingPublicKey#
Bases:
PublicKeyPlaceholder class for unsupported public key types.
This class serves as a fallback implementation that raises an exception when instantiated, indicating that the specific key type is not supported by the SPSDK crypto module.
Initialize unsupported key type constructor.
This constructor is designed to immediately raise an exception to indicate that the specific key type is not supported or implemented in the current version of SPSDK.
- Raises:
SPSDKNotImplementedError – The key type is not supported or implemented.
- class spsdk.crypto.keys.PQCKey(key)#
Bases:
objectPost-Quantum Cryptography key wrapper for SPSDK operations.
This class provides a unified interface for working with post-quantum cryptographic keys, supporting both Dilithium and ML-DSA key types. It handles key operations including signature verification and provides access to key properties and metadata.
- Variables:
SUPPORTED_LEVELS – List of supported security levels for PQC algorithms.
RECOMMENDED_ENCODING – Preferred encoding format for key serialization.
Initialize PQC key.
- Parameters:
key (
Union[DilithiumPrivateKey,DilithiumPublicKey,MLDSAPublicKey]) – The post-quantum cryptography key object to initialize with.- Raises:
TypeError – If the provided key is not a supported PQC key type.
- RECOMMENDED_ENCODING = 'PEM'#
- SUPPORTED_LEVELS = [2, 3, 5]#
- property default_hash_algorithm: EnumHashAlgorithm#
Get default hash algorithm for signing and verifying operations.
- Returns:
Default hash algorithm enumeration value (SHA384).
-
key:
Union[DilithiumPrivateKey,DilithiumPublicKey,MLDSAPublicKey]#
- property key_size: int#
Get the key size in bytes.
- Returns:
Size of the key in bytes.
- property level: int#
Get Key level.
- Returns:
The level of the key.
- property public_numbers: bytes#
Get public numbers of the cryptographic key.
Returns the public data portion of the key as raw bytes, which contains the public key material that can be shared openly.
- Returns:
Raw bytes containing the public key data.
- property signature_size: int#
Get the size of signature data in bytes.
- Returns:
Size of the signature in bytes.
- verify_signature(signature, data, algorithm=None, prehashed=False, **kwargs)#
Verify signature against input data using the public key.
The method supports both raw data and pre-hashed data verification. When prehashed is False, the data will be hashed using the specified or default algorithm before verification.
- Parameters:
signature (
bytes) – The signature bytes to verify against the data.data (
bytes) – Input data to verify or pre-hashed data if prehashed is True.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm to use, defaults to key’s default algorithm.prehashed (
bool) – Whether the input data is already hashed.kwargs (
Any) – Additional keyword arguments for specific key types.
- Return type:
bool- Returns:
True if signature is valid, False otherwise.
- class spsdk.crypto.keys.PQCPrivateKey(key)#
Bases:
PQCKey,PrivateKeySPSDK Post-Quantum Cryptography private key wrapper.
This class provides a unified interface for PQC private key operations including digital signing and key export functionality. It wraps underlying PQC private key implementations (Dilithium, ML-DSA) and provides standardized methods for cryptographic operations across different PQC algorithms.
Initialize PQC key.
- Parameters:
key (
Union[DilithiumPrivateKey,DilithiumPublicKey,MLDSAPublicKey]) – The post-quantum cryptography key object to initialize with.- Raises:
TypeError – If the provided key is not a supported PQC key type.
- export(password=None, encoding=<SPSDKEncoding.DER: 'DER'>)#
Export key into bytes to requested format.
- Parameters:
password (
Optional[str]) – Password to private key; None to store without password.encoding (
SPSDKEncoding) – Encoding type, defaults to DER.
- Return type:
bytes- Returns:
Byte representation of key.
-
key:
Union[DilithiumPrivateKey,MLDSAPrivateKey]#
- sign(data, algorithm=None, prehashed=False, **kwargs)#
Sign input data with the private key.
The method supports both raw data signing and pre-hashed data signing based on the prehashed parameter. When prehashed is False, the data is hashed using the specified or default algorithm before signing.
- Parameters:
data (
bytes) – Input data to be signed or pre-hashed data if prehashed is True.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm to use for data hashing, uses default if None.prehashed (
bool) – If True, treats input data as already hashed.kwargs (
Any) – Additional keyword arguments for specific key implementations.
- Return type:
bytes- Returns:
Digital signature as bytes.
- class spsdk.crypto.keys.PQCPublicKey(key)#
-
Post-Quantum Cryptography public key wrapper.
This class provides a unified interface for handling PQC public keys, supporting both Dilithium and ML-DSA algorithms. It manages key export operations and provides comparison functionality for PQC public keys.
Initialize PQC key.
- Parameters:
key (
Union[DilithiumPrivateKey,DilithiumPublicKey,MLDSAPublicKey]) – The post-quantum cryptography key object to initialize with.- Raises:
TypeError – If the provided key is not a supported PQC key type.
- export(encoding=<SPSDKEncoding.NXP: 'NXP'>)#
Export key into bytes to requested format.
The method supports multiple encoding formats including NXP proprietary format and PEM format.
- Parameters:
encoding (
SPSDKEncoding) – Encoding type for key export, defaults to SPSDKEncoding.NXP.- Return type:
bytes- Returns:
Byte representation of the exported key.
-
key:
Union[DilithiumPublicKey,MLDSAPublicKey]#
- class spsdk.crypto.keys.PrivateKey#
Bases:
BaseClass,ABCSPSDK Private Key abstract base class.
This abstract class defines the interface for private key operations in SPSDK, providing cryptographic functionality for signing operations and key management across different key types and algorithms.
- classmethod create(key)#
Create Private Key object from supported cryptographic key types.
This factory method creates an appropriate SPSDK private key wrapper based on the input key type. It supports ECC, RSA, SM2 (if OSCCA is available), and post-quantum Dilithium/ML-DSA keys (if Dilithium support is available).
- Parameters:
key (
Any) – A cryptographic private key object (ECC, RSA, SM2, Dilithium, or ML-DSA).- Raises:
SPSDKInvalidKeyType – Unsupported private key type provided.
- Return type:
Self- Returns:
SPSDK Private Key object wrapping the input key.
- abstract property default_hash_algorithm: EnumHashAlgorithm#
Get default hash algorithm for signing and verifying operations.
- Returns:
Default hash algorithm enumeration value.
- abstract export(password=None, encoding=<SPSDKEncoding.DER: 'DER'>)#
Export key into bytes in requested format.
- Parameters:
password (
Optional[str]) – Password to private key; None to store without password.encoding (
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 instance.
- abstract get_public_key()#
Get public key from the private key.
- Return type:
- Returns:
Public key object derived from this private key.
-
key:
Any#
- abstract property key_size: int#
Get key size in bits.
- Returns:
Key size in bits.
- 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 stored.password (
Optional[str]) – Password to private key; None to load without password.
- Raises:
SPSDKError – If the file cannot be loaded or parsed.
- Return type:
Self- Returns:
Loaded private key instance.
- classmethod parse(data, password=None)#
Parse private key from bytes array.
The method supports multiple encodings (PEM, DER) and various key types including RSA, ECC, SM2, Dilithium, and ML-DSA private keys.
- Parameters:
data (
bytes) – Raw key data to be parsed.password (
Optional[str]) – Password for encrypted private key; None for unencrypted keys.
- Return type:
Self- Returns:
Recreated private key object.
- Raises:
SPSDKError – Invalid key data or unsupported key type.
- save(file_path, password=None, encoding=<SPSDKEncoding.PEM: 'PEM'>)#
Save the Private key to the given file.
- Parameters:
file_path (
str) – Path to the file where the key will be stored.password (
Optional[str]) – Password to encrypt private key; None to store without password.encoding (
SPSDKEncoding) – Encoding type for the saved key, default is PEM.
- Raises:
SPSDKError – If the file cannot be written or key export fails.
- Return type:
None
- abstract sign(data, **kwargs)#
Sign input data with the cryptographic key.
This method performs cryptographic signing of the provided data using the underlying key material and algorithm.
- Parameters:
data (
bytes) – Input data to be signed.kwargs (
Any) – Additional keyword arguments specific to the key type and signing algorithm.
- Return type:
bytes- Returns:
Digital signature of the input data.
- abstract property signature_size: int#
Get the size of signature data in bytes.
- Returns:
Size of signature data in bytes.
- abstract verify_public_key(public_key)#
Verify that the given public key forms a cryptographic pair with this private key.
This method checks if the provided public key corresponds to this private key by verifying their mathematical relationship in the cryptographic key pair.
- Parameters:
public_key (
PublicKey) – Public key to verify against this private key.- Return type:
bool- Returns:
True if the keys form a valid pair, False otherwise.
- class spsdk.crypto.keys.PrivateKeyDilithium(key)#
Bases:
PQCPrivateKeySPSDK Dilithium private key implementation for post-quantum cryptography.
This class provides a wrapper around Dilithium private keys, enabling generation, parsing, and cryptographic operations with post-quantum security.
Initialize PQC key.
- Parameters:
key (
Union[DilithiumPrivateKey,DilithiumPublicKey,MLDSAPublicKey]) – The post-quantum cryptography key object to initialize with.- Raises:
TypeError – If the provided key is not a supported PQC key type.
- classmethod generate_key(level=None, algorithm=None)#
Generate SPSDK Key (private key).
One of ‘level’ or ‘algorithm’ must be specified.
- Parameters:
level (
Optional[int]) – NIST claim level, defaults to Nonealgorithm (
Optional[PQCAlgorithm]) – Exact PQC algorithm to use, defaults to None
- Raises:
SPSDKError – Could not create Dilithium key
- Return type:
Self- Returns:
Dilithium Private key
- get_public_key()#
Get the public key from the Dilithium private key.
Extracts and returns the public key portion from this Dilithium private key instance.
- Raises:
SPSDKUnsupportedOperation – When the Dilithium key doesn’t have public portion.
- Return type:
- Returns:
Public key instance containing the Dilithium public key data.
-
key:
DilithiumPrivateKey#
- classmethod parse(data, password=None)#
Parse object from bytes array.
- Parameters:
data (
bytes) – Data to be parsed.password (
Optional[str]) – Password in case of encrypted key.
- Raises:
SPSDKError – Could not parse key.
- Return type:
Self- Returns:
Recreated key.
- verify_public_key(public_key)#
Verify that the provided public key matches this key’s public key.
This method checks if the given public key is of the correct Dilithium type and compares the public key data to determine if they are identical.
- Parameters:
public_key (
PublicKey) – The public key to verify against this key.- Raises:
SPSDKInvalidKeyType – If the public key is not a Dilithium public key.
- Return type:
bool- Returns:
True if the public keys match, False otherwise.
- class spsdk.crypto.keys.PrivateKeyEcc(key)#
Bases:
KeyEccCommon,PrivateKeySPSDK ECC Private Key implementation.
This class provides elliptic curve cryptography private key operations for SPSDK, including key generation, ECDH key exchange, digital signatures, and public key derivation. It wraps cryptographic operations for secure provisioning workflows.
Create SPSDK ECC Private Key.
Initialize an SPSDK ECC private key wrapper with the provided cryptographic key.
- Parameters:
key (
EllipticCurvePrivateKey) – ECC private key object from cryptography library.- Raises:
TypeError – If the provided key is not an ECC private key.
- property d: int#
Get the private number D from the RSA key.
- Returns:
The private value D component of the RSA private key.
- exchange(peer_public_key)#
Exchange key using ECDH algorithm with provided peer public key.
- Parameters:
peer_public_key (
PublicKeyEcc) – Peer public key for ECDH key exchange.- Return type:
bytes- Returns:
Shared secret key as bytes.
- export(password=None, encoding=<SPSDKEncoding.DER: 'DER'>)#
Export the Private key to the bytes in requested format.
The method supports multiple encoding formats including DER, PEM, and NXP-specific format. For NXP encoding, only the raw private scalar ‘d’ is exported.
- Parameters:
password (
Optional[str]) – Password to encrypt the private key; None to store without password.encoding (
SPSDKEncoding) – Encoding type for the exported key, default is DER.
- Return type:
bytes- Returns:
Private key in bytes format.
- classmethod generate_key(curve_name=EccCurve.SECP256R1)#
Generate SPSDK Key (private key).
Creates a new private key using the specified elliptic curve for cryptographic operations.
- Parameters:
curve_name (
EccCurve) – Name of the elliptic curve to use for key generation, defaults to SECP256R1- Return type:
Self- Returns:
SPSDK private key instance
- get_public_key()#
Get public key from private key.
Extracts the corresponding public key from this private key instance.
- Return type:
- Returns:
Public key derived from this private key.
-
key:
EllipticCurvePrivateKey#
- classmethod parse(data, password=None)#
Parse ECC private key object from bytes array.
The method parses the provided byte data to recreate an ECC private key object. It validates that the parsed key is specifically an ECC private key type.
- Parameters:
data (
bytes) – Raw byte data containing the key information to be parsed.password (
Optional[str]) – Optional password for encrypted private key; None for unencrypted keys.
- Raises:
SPSDKInvalidKeyType – When the data cannot be parsed as an ECC private key.
- Return type:
Self- Returns:
Recreated ECC private key object.
- 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, **kwargs)#
Sign input data with the private key using ECDSA algorithm.
The method supports both raw data and pre-hashed input data signing. Output format can be either DER or serialized signature format.
- Parameters:
data (
bytes) – Input data to be signed or pre-hashed value if prehashed is True.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm to use for signing, defaults to key’s default algorithm.der_format (
bool) – If True, return signature in DER format, otherwise use serialized format.prehashed (
bool) – If True, treat input data as already hashed value.kwargs (
Any) – Additional unused arguments for compatibility.
- Return type:
bytes- Returns:
Digital signature as bytes in specified format.
- verify_public_key(public_key)#
Verify that the given public key matches this private key.
This method compares the provided public key with the public key derived from this private key to determine if they form a valid key pair.
- Parameters:
public_key (
PublicKey) – Public key to verify against this private key- Return type:
bool- Returns:
True if the keys form a valid pair, False otherwise
- class spsdk.crypto.keys.PrivateKeyMLDSA(key)#
Bases:
PQCPrivateKeyML-DSA Private Key for post-quantum cryptographic operations.
This class provides a wrapper around ML-DSA (Module-Lattice-Based Digital Signature Algorithm) private keys, enabling key generation, public key derivation, verification, and serialization operations within the SPSDK framework.
Initialize PQC key.
- Parameters:
key (
Union[DilithiumPrivateKey,DilithiumPublicKey,MLDSAPublicKey]) – The post-quantum cryptography key object to initialize with.- Raises:
TypeError – If the provided key is not a supported PQC key type.
- classmethod generate_key(level=None, algorithm=None)#
Generate SPSDK Key (private key).
One of ‘level’ or ‘algorithm’ must be specified.
- Parameters:
level (
Optional[int]) – NIST claim level, defaults to Nonealgorithm (
Optional[PQCAlgorithm]) – Exact PQC algorithm to use, defaults to None
- Raises:
SPSDKError – Could not create Dilithium key
- Return type:
Self- Returns:
ML-DSA Private key
- get_public_key()#
Get the public key from the Dilithium private key.
Extracts and returns the public key portion of the ML-DSA (Dilithium) key pair.
- Raises:
SPSDKUnsupportedOperation – When the Dilithium key doesn’t have a public portion.
- Return type:
- Returns:
The public key as PublicKeyMLDSA instance.
-
key:
MLDSAPrivateKey#
- classmethod parse(data, password=None)#
Parse MLDSA private key object from bytes array.
- Parameters:
data (
bytes) – Raw bytes data containing the MLDSA private key to be parsed.password (
Optional[str]) – Optional password for encrypted key decryption.
- Raises:
SPSDKError – When the key parsing fails or data is invalid.
- Return type:
Self- Returns:
Recreated MLDSA private key object.
- verify_public_key(public_key)#
Verify that the provided public key matches this private key.
The method checks if the public key is of the correct type (Dilithium/ML-DSA) and compares the public data to ensure it corresponds to this private key.
- Parameters:
public_key (
PublicKey) – The public key to verify against this private key.- Raises:
SPSDKInvalidKeyType – If the public key is not a Dilithium public key.
- Return type:
bool- Returns:
True if the public key matches this private key, False otherwise.
- class spsdk.crypto.keys.PrivateKeyRsa(key)#
Bases:
PrivateKeySPSDK RSA Private Key implementation.
This class provides RSA private key functionality for cryptographic operations including key generation, signing, and public key derivation. It supports standard RSA key sizes and integrates with SPSDK’s cryptographic framework.
- Variables:
SUPPORTED_KEY_SIZES – List of supported RSA key sizes in bits.
Create SPSDK RSA private key wrapper.
Initialize the SPSDK key object with an RSA private key for cryptographic operations.
- Parameters:
key (
RSAPrivateKey) – RSA private key instance to be wrapped by SPSDK key object.
- SUPPORTED_KEY_SIZES = [2048, 3072, 4096]#
- property default_hash_algorithm: EnumHashAlgorithm#
Get default hash algorithm for signing/verifying operations.
- Returns:
Default hash algorithm enumeration value (SHA256).
- export(password=None, encoding=<SPSDKEncoding.DER: 'DER'>)#
Export the Private key to the bytes in requested encoding.
- Parameters:
password (
Optional[str]) – Password to private key; None to store without password.encoding (
SPSDKEncoding) – Encoding type, default is DER.
- Return type:
bytes- Returns:
Private key in bytes.
- classmethod generate_key(key_size=2048, exponent=65537)#
Generate SPSDK RSA private key.
This method creates a new RSA private key with specified parameters for use in SPSDK cryptographic operations.
- Parameters:
key_size (
int) – Key size in bits, must be >= 512.exponent (
int) – Public exponent, must be >= 3 and odd.
- Return type:
Self- Returns:
New SPSDK private key instance.
- get_public_key()#
Get public key from RSA private key.
Extracts the public key component from the RSA private key instance.
- Return type:
- Returns:
RSA public key object.
-
key:
RSAPrivateKey#
- property key_size: int#
Key size in bits.
- Returns:
Key size in bits.
- classmethod parse(data, password=None)#
Parse RSA private key from bytes array.
The method parses binary data to recreate an RSA private key object with optional password protection support.
- Parameters:
data (
bytes) – Binary data containing the RSA private key to be parsed.password (
Optional[str]) – Password for encrypted private key; None for unencrypted keys.
- Raises:
SPSDKInvalidKeyType – When the data cannot be parsed as RSA private key.
- Return type:
Self- Returns:
Recreated RSA private key object.
- sign(data, algorithm=None, pss_padding=False, prehashed=False, **kwargs)#
Sign input data with the private key.
The method supports both PKCS#1 v1.5 and PSS padding schemes for RSA keys. It can handle both raw data and pre-hashed data depending on the prehashed parameter.
- Parameters:
data (
bytes) – Input data to be signed.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm to use for signing, defaults to key’s default algorithm.pss_padding (
bool) – Whether to use RSA-PSS padding scheme instead of PKCS#1 v1.5.prehashed (
bool) – Whether the input data is already hashed.kwargs (
Any) – Additional unused parameters for compatibility.
- Return type:
bytes- Returns:
Digital signature as bytes.
- property signature_size: int#
Get the size of signature data in bytes.
- Returns:
Size of signature data in bytes.
- verify_public_key(public_key)#
Verify that the given public key matches this private key.
This method compares the provided public key with the public key derived from this private key to determine if they form a valid key pair.
- Parameters:
public_key (
PublicKey) – Public key to verify against this private key- Return type:
bool- Returns:
True if the keys form a valid pair, False otherwise
- class spsdk.crypto.keys.PrivateKeySM2(key)#
Bases:
PrivateKeySPSDK SM2 Private Key implementation.
This class provides SM2 elliptic curve private key operations for cryptographic functions including key generation, signing, and public key derivation. SM2 is a Chinese national standard for elliptic curve cryptography.
Create SPSDK Key with SM2 cryptographic key.
- Parameters:
key (
CryptSM2) – SM2 cryptographic key instance to be wrapped by SPSDK Key.- Raises:
SPSDKInvalidKeyType – If the provided key is not of SM2 type.
- property default_hash_algorithm: EnumHashAlgorithm#
Get default hash algorithm for signing and verifying operations.
Returns the SM3 hash algorithm as the default choice for cryptographic operations with this key type.
- Returns:
SM3 hash algorithm enum value.
- export(password=None, encoding=<SPSDKEncoding.DER: 'DER'>)#
Export SM2 private key to bytes format supported by NXP.
The method exports the SM2 private key using DER encoding, which is the only supported encoding format for SM2 keys in NXP systems.
- Parameters:
password (
Optional[str]) – Password for key encryption (currently not used for SM2 keys).encoding (
SPSDKEncoding) – Encoding format for the exported key, only DER is supported.
- Raises:
SPSDKNotImplementedError – When encoding other than DER is requested.
- Return type:
bytes- Returns:
SM2 private key encoded as bytes in DER format.
- classmethod generate_key()#
Generate SM2 cryptographic key pair.
Creates a new SM2 private key with corresponding public key using secure random generation. The method ensures the generated public key meets SM2 format requirements.
- Return type:
Self- Returns:
New SM2 key instance with generated private and public key pair.
- get_public_key()#
Get public key from private key.
Extracts the public key component from the SM2 private key and wraps it in a PublicKeySM2 object for cryptographic operations.
- Return type:
- Returns:
Public key object containing the SM2 public key.
-
key:
CryptSM2#
- property key_size: int#
Get the size of the key in bits.
- Returns:
Size of the key in bits.
- save(file_path, password=None, encoding=<SPSDKEncoding.PEM: 'PEM'>)#
Save the Private key to the given file.
Saves the private key to a file in DER encoding format regardless of the encoding parameter specified.
- Parameters:
file_path (
str) – Path where the private key file will be saved.password (
Optional[str]) – Optional password for encrypting the private key file.encoding (
SPSDKEncoding) – Encoding format (parameter ignored, always saves as DER).
- Return type:
None
- sign(data, salt=None, use_ber=False, **kwargs)#
Sign data using SM2 algorithm with SM3 hash.
The method uses SM3 hash function to process the input data and generates a digital signature using the SM2 elliptic curve cryptography algorithm.
- 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 False.kwargs (
Any) – Sink for unused arguments.
- Raises:
SPSDKError – Signature can’t be created.
- Return type:
bytes- Returns:
SM2 signature in raw or BER format.
- property signature_size: int#
Get the signature size in bytes.
- Returns:
Size of the signature in bytes (always 64 for this implementation).
- verify_public_key(public_key)#
Verify that the given public key corresponds to this private key.
This method checks if the provided public key forms a valid cryptographic key pair with the current private key by comparing it with the derived public key.
- Parameters:
public_key (
PublicKey) – Public key to verify against this private key.- Return type:
bool- Returns:
True if the keys form a valid pair, False otherwise.
- class spsdk.crypto.keys.PublicKey#
Bases:
BaseClass,ABCSPSDK Public Key abstraction for cryptographic operations.
This abstract base class provides a unified interface for public key operations across different cryptographic algorithms and key types. It handles key loading, saving, signature verification, and key format conversions while maintaining consistency across the SPSDK cryptographic framework.
- Variables:
RECOMMENDED_ENCODING – Default encoding format for key serialization.
- RECOMMENDED_ENCODING = 'PEM'#
- classmethod create(key)#
Create Public Key object from supported key types.
This factory method creates an appropriate SPSDK Public Key wrapper object based on the type of the input key. It supports various key types including ECC, RSA, SM2 (if OSCCA is supported), and post-quantum algorithms like Dilithium and ML-DSA (if available).
- Parameters:
key (
Any) – A supported public key object (ECC, RSA, SM2, Dilithium, or ML-DSA).- Raises:
SPSDKInvalidKeyType – Unsupported public key type provided.
- Return type:
Self- Returns:
SPSDK Public Key object wrapping the input key.
- abstract property default_hash_algorithm: EnumHashAlgorithm#
Get default hash algorithm for signing/verifying.
- Returns:
Default hash algorithm enumeration value.
- abstract export(encoding=<SPSDKEncoding.NXP: 'NXP'>)#
Export key into bytes to requested format.
- Parameters:
encoding (
SPSDKEncoding) – Encoding type for the exported key data, defaults to NXP format.- Return type:
bytes- Returns:
Byte representation of the key in specified encoding format.
-
key:
Any#
- key_hash(algorithm=EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'))#
Get key hash.
Computes hash of the exported key data using the specified hash algorithm.
- Parameters:
algorithm (
EnumHashAlgorithm) – Hash algorithm to use for key hashing, defaults to SHA256.- Return type:
bytes- Returns:
Hash of the key data as bytes.
- classmethod load(file_path)#
Load the Public key from the given file.
The method loads binary data from the specified file path and parses it to create a public key instance.
- Parameters:
file_path (
str) – Path to the file where the key is stored.- Raises:
SPSDKError – If the file cannot be loaded or parsed.
- Return type:
Self- Returns:
Public key instance created from the file data.
- classmethod parse(data)#
Parse public key from bytes array.
Attempts to parse public key data from various formats including PEM, DER, ECC, RSA, Dilithium, ML-DSA, and NXP OTPS formats.
- Parameters:
data (
bytes) – Raw bytes containing public key data in supported format.- Return type:
Self- Returns:
Parsed public key object.
- Raises:
SPSDKError – Unable to parse public key data from any supported format.
- abstract property public_numbers: Any#
Get the public numbers of the cryptographic key.
Returns the public key numbers which contain the mathematical components that make up the public portion of the key.
- Returns:
Public key numbers object containing the key’s mathematical components.
- save(file_path, encoding=<SPSDKEncoding.PEM: 'PEM'>)#
Save the public key to the file.
- Parameters:
file_path (
str) – Path to the file where the key will be stored.encoding (
SPSDKEncoding) – Encoding type for the key export, defaults to PEM.
- Raises:
SPSDKError – If the file cannot be written or export fails.
- Return type:
None
- abstract property signature_size: int#
Get the size of signature data in bytes.
- Returns:
Size of signature data in bytes.
- abstract verify_signature(signature, data, algorithm=None, **kwargs)#
Verify signature against input data using cryptographic algorithm.
The method validates the provided signature against the input data using the specified or automatically selected hash algorithm.
- Parameters:
signature (
bytes) – The signature bytes to verify against the data.data (
bytes) – Input data bytes that were signed.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm to use for verification, defaults to automatic selection.kwargs (
Any) – Additional keyword arguments specific to the key type.
- Return type:
bool- Returns:
True if signature is valid, False otherwise.
- class spsdk.crypto.keys.PublicKeyDilithium(key)#
Bases:
PQCPublicKeyDilithium Public Key implementation for post-quantum cryptography.
This class provides a wrapper for Dilithium public keys, enabling parsing and handling of Dilithium public key data within the SPSDK framework. Dilithium is a post-quantum digital signature algorithm designed to be secure against quantum computer attacks.
Initialize PQC key.
- Parameters:
key (
Union[DilithiumPrivateKey,DilithiumPublicKey,MLDSAPublicKey]) – The post-quantum cryptography key object to initialize with.- Raises:
TypeError – If the provided key is not a supported PQC key type.
-
key:
DilithiumPublicKey#
- classmethod parse(data)#
Parse Dilithium public key object from bytes array.
- Parameters:
data (
bytes) – Raw bytes data containing the Dilithium public key to be parsed.- Raises:
SPSDKInvalidKeyType – Invalid or corrupted Dilithium public key data.
- Return type:
Self- Returns:
Recreated Dilithium public key object.
- class spsdk.crypto.keys.PublicKeyEcc(key)#
Bases:
KeyEccCommon,PublicKeySPSDK ECC Public Key implementation.
This class provides functionality for handling Elliptic Curve Cryptography (ECC) public keys within the SPSDK framework. It supports key export in various formats, signature verification, and coordinate extraction for cryptographic operations across NXP MCU portfolio.
Create SPSDK Public Key.
- Parameters:
key (
EllipticCurvePublicKey) – Elliptic curve public key instance.- Raises:
SPSDKError – Invalid key provided.
- export(encoding=<SPSDKEncoding.NXP: 'NXP'>)#
Export the public key to bytes in requested format.
The method supports NXP encoding (concatenated x and y coordinates) and standard cryptographic encodings through the cryptography library.
- Parameters:
encoding (
SPSDKEncoding) – Encoding type for the exported key, defaults to SPSDKEncoding.NXP- Return type:
bytes- Returns:
Public key exported as bytes in the specified format
-
key:
EllipticCurvePublicKey#
- classmethod parse(data)#
Parse ECC public key object from bytes array.
Attempts to parse the data using the parent class method first. If that fails or doesn’t return a PublicKeyEcc instance, falls back to recreating the key from the raw data.
- Parameters:
data (
bytes) – Raw bytes data containing the ECC public key information.- Raises:
SPSDKInvalidKeyType – When the data cannot be parsed as an ECC public key.
- Return type:
Self- Returns:
Recreated ECC public key object.
- property public_numbers: EllipticCurvePublicNumbers#
Get public numbers of the elliptic curve key.
- Returns:
Public numbers containing the x and y coordinates of the public key point.
- 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.
- Raises:
SPSDKValueError – Invalid coordinates or curve parameters.
- Return type:
Self- Returns:
ECC public key.
- classmethod recreate_from_data(data, curve=None)#
Recreate ECC public key from coordinates in data blob.
The method supports both raw binary format (X,Y coordinates in Big Endian) and DER format. If curve is not specified, the method will attempt to determine it from data length.
- Parameters:
data (
bytes) – Data blob of coordinates in bytes (X,Y in Big Endian) or DER format.curve (
Optional[EccCurve]) – ECC curve, if None the curve will be auto-detected from data length.
- Raises:
SPSDKUnsupportedEccCurve – When curve cannot be determined from data length.
- Return type:
Self- Returns:
ECC public key instance.
- verify_signature(signature, data, algorithm=None, prehashed=False, **kwargs)#
Verify signature against input data using ECDSA algorithm.
The method supports both raw signature format (r||s coordinates) and DER-encoded signatures. It automatically converts raw signatures to DER format for verification.
- Parameters:
signature (
bytes) – The signature bytes to verify against the data.data (
bytes) – Input data that was signed.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm to use for verification. If None, uses default.prehashed (
bool) – Whether the input data is already hashed.kwargs (
Any) – Additional unused arguments for compatibility.
- Return type:
bool- Returns:
True if signature is valid, False otherwise.
- property x: int#
Get the X coordinate of the public key point.
- Returns:
X coordinate value of the elliptic curve public key point.
- property y: int#
Get the Y coordinate of the public key point.
- Returns:
Y coordinate value of the elliptic curve public key point.
- class spsdk.crypto.keys.PublicKeyMLDSA(key)#
Bases:
PQCPublicKeyML-DSA (Module-Lattice-Based Digital Signature Algorithm) public key implementation.
This class provides a wrapper for ML-DSA public keys, offering parsing capabilities and integration with the SPSDK cryptographic framework. ML-DSA is a post-quantum cryptographic signature algorithm designed to be secure against quantum attacks.
Initialize PQC key.
- Parameters:
key (
Union[DilithiumPrivateKey,DilithiumPublicKey,MLDSAPublicKey]) – The post-quantum cryptography key object to initialize with.- Raises:
TypeError – If the provided key is not a supported PQC key type.
-
key:
MLDSAPublicKey#
- classmethod parse(data)#
Parse MLDSA public key object from bytes array.
- Parameters:
data (
bytes) – Raw bytes data containing the MLDSA public key to be parsed.- Raises:
SPSDKError – If the key data cannot be parsed or is invalid.
- Return type:
Self- Returns:
Recreated MLDSA public key instance.
- class spsdk.crypto.keys.PublicKeyRsa(key)#
Bases:
PublicKeySPSDK RSA Public Key implementation.
This class provides RSA public key operations for cryptographic functions including signature verification and key property access. It wraps the cryptography library’s RSA public key with SPSDK-specific functionality.
Create SPSDK Public Key.
- Parameters:
key (
RSAPublicKey) – RSA public key object to be wrapped by SPSDK.- Raises:
SPSDKError – If the provided key is invalid or unsupported.
- property default_hash_algorithm: EnumHashAlgorithm#
Get default hash algorithm for signing and verifying operations.
- Returns:
Default hash algorithm enumeration value (SHA256).
- property e: int#
Get the public exponent E of the RSA key.
The public exponent E is a component of the RSA public key used in cryptographic operations for encryption and signature verification.
- Returns:
The public exponent E as an integer.
- export(encoding=<SPSDKEncoding.NXP: 'NXP'>, exp_length=None, modulus_length=None)#
Export the public key to bytes in specified format.
The method supports both NXP proprietary format (modulus + exponent) and standard DER format. For NXP encoding, the output contains modulus followed by exponent in big-endian byte order.
- Parameters:
encoding (
SPSDKEncoding) – Encoding format for the exported key, defaults to NXP format.exp_length (
Optional[int]) – Optional specific exponent length in bytes for NXP format.modulus_length (
Optional[int]) – Optional specific modulus length in bytes for NXP format.
- Return type:
bytes- Returns:
Public key exported as bytes in the specified format.
-
key:
RSAPublicKey#
- property key_size: int#
Key size in bits.
- Returns:
Key size in bits.
- property n: int#
Get the RSA public key modulus N.
The modulus N is one of the two components of an RSA public key, representing the product of two prime numbers used in RSA encryption and signature operations.
- Returns:
The RSA public key modulus as an integer.
- classmethod parse(data)#
Parse RSA public key from bytes array.
Attempts to parse the data using the parent class method first. If that fails, tries to recreate the RSA public key using RSA-specific parsing methods.
- Parameters:
data (
bytes) – Raw bytes data containing the RSA public key information.- Raises:
SPSDKInvalidKeyType – When the data cannot be parsed as RSA public key.
- Return type:
Self- Returns:
Recreated RSA public key instance.
- property public_numbers: RSAPublicNumbers#
Public numbers of key.
- 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 instance.
- classmethod recreate_from_data(data)#
Recreate RSA public key from exponent and modulus in data blob.
- Parameters:
data (
bytes) – Data blob containing exponent and modulus in bytes (Big Endian format).- Return type:
Self- Returns:
RSA public key instance.
- static recreate_public_numbers(data)#
Recreate RSA public numbers from raw key data.
The method attempts to parse the input data as an RSA public key by trying different supported key sizes and extracting the modulus (n) and exponent (e) components.
- Parameters:
data (
bytes) – Raw key data containing modulus and exponent in big-endian format.- Raises:
SPSDKError – Unrecognized data format or unsupported key size.
- Return type:
RSAPublicNumbers- Returns:
RSA public numbers object containing the extracted key components.
- property signature_size: int#
Get the size of signature data in bytes.
- Returns:
Size of signature data in bytes.
- verify_signature(signature, data, algorithm=None, pss_padding=False, prehashed=False, **kwargs)#
Verify signature against provided data using RSA cryptographic verification.
The method supports both PKCS#1 v1.5 and PSS padding schemes, with configurable hash algorithms and pre-hashed data verification.
- Parameters:
signature (
bytes) – The signature bytes to verify against the data.data (
bytes) – Input data bytes to verify signature against.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm to use for verification, defaults to key’s default.pss_padding (
bool) – Use RSA-PSS padding scheme instead of PKCS#1 v1.5.prehashed (
bool) – Indicates if data is already hashed and ready for verification.kwargs (
Any) – Additional unused parameters for compatibility.
- Return type:
bool- Returns:
True if signature is valid, False otherwise.
- class spsdk.crypto.keys.PublicKeySM2(key)#
Bases:
PublicKeySM2 Public Key implementation for SPSDK cryptographic operations.
This class provides SM2 elliptic curve public key functionality including signature verification and key export operations. SM2 is a Chinese national standard for elliptic curve cryptography.
- Variables:
RECOMMENDED_ENCODING – Default encoding format for SM2 key export operations.
Create SPSDK Public Key from SM2 cryptographic key.
- Parameters:
key (
CryptSM2) – SM2 cryptographic key instance to wrap.- Raises:
SPSDKInvalidKeyType – If the provided key is not an SM2 type.
- RECOMMENDED_ENCODING = 'DER'#
- property default_hash_algorithm: EnumHashAlgorithm#
Get default hash algorithm for signing and verifying operations.
Returns the SM3 hash algorithm as the default choice for cryptographic operations with this key type.
- Returns:
SM3 hash algorithm enum value.
- export(encoding=<SPSDKEncoding.DER: 'DER'>)#
Convert key into bytes supported by NXP.
Exports the SM2 key in the specified encoding format. Currently only DER encoding is supported for SM2 keys.
- Parameters:
encoding (
SPSDKEncoding) – The encoding format to use for export.- Raises:
SPSDKNotImplementedError – If encoding other than DER is requested.
- Return type:
bytes- Returns:
Byte representation of the SM2 public key in DER format.
-
key:
CryptSM2#
- property public_numbers: str#
Get the public numbers of the cryptographic key.
- Returns:
Public numbers representation of the key.
- classmethod recreate(data)#
Recreate SM2 public key from data.
- Parameters:
data (
bytes) – Raw bytes containing the SM2 public key data to be reconstructed.- Return type:
Self- Returns:
New SPSDK SM2 public key instance created from the provided data.
- classmethod recreate_from_data(data)#
Recreate SM2 public key from data.
The method creates a new SM2 public key instance from PEM or DER encoded key data. It sanitizes the input data and decodes it using SM2Encoder.
- Parameters:
data (
bytes) – PEM or DER encoded key data as bytes.- Return type:
Self- Returns:
New SM2 public key instance.
- save(file_path, encoding=<SPSDKEncoding.PEM: 'PEM'>)#
Save the Private key to the given file.
- Parameters:
file_path (
str) – Path to the file where the private key will be saved.encoding (
SPSDKEncoding) – Encoding format for the key (defaults to PEM, but saves as DER).
- Return type:
None
- property signature_size: int#
Get the signature size in bytes.
- Returns:
Size of the signature in bytes (always 64 for this implementation).
- verify_signature(signature, data, algorithm=None, **kwargs)#
Verify SM2 signature against provided data.
The method supports both BER-formatted signatures (starting with 0x30) and raw format signatures (r || s concatenated). The data is hashed using SM3 algorithm before verification.
- Parameters:
signature (
bytes) – SM2 signature to verify in BER or raw format.data (
bytes) – Original data that was signed.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm parameter for compatibility with abstract class.kwargs (
Any) – Additional unused arguments.
- Raises:
SPSDKError – Invalid signature format or verification failure.
- Return type:
bool- Returns:
True if signature is valid, False otherwise.
- exception spsdk.crypto.keys.SPSDKInvalidKeyType(desc=None)#
Bases:
SPSDKErrorSPSDK exception for invalid cryptographic key types.
This exception is raised when an unsupported or invalid key type is encountered during cryptographic operations in SPSDK.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.crypto.keys.SPSDKKeyPassphraseMissing(desc=None)#
Bases:
SPSDKErrorSPSDK exception for missing private key passphrase.
This exception is raised when a passphrase is required to decrypt a private key but none has been provided during cryptographic operations.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.crypto.keys.SPSDKUnsupportedEccCurve(desc=None)#
Bases:
SPSDKValueErrorSPSDK exception for unsupported ECC curve operations.
This exception is raised when an operation is attempted with an ECC curve that is not supported by the SPSDK cryptographic functionality.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.crypto.keys.SPSDKWrongKeyPassphrase(desc=None)#
Bases:
SPSDKErrorSPSDK exception for incorrect private key passphrase.
This exception is raised when an incorrect or invalid passphrase is provided for decrypting a private key during cryptographic operations.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- spsdk.crypto.keys.get_ecc_curve(key_length)#
Get ECC curve based on key length.
Determines the appropriate elliptic curve cryptography curve type based on the provided key length in bytes. Supports SECP256R1, SECP384R1, and SECP521R1 curves.
- Parameters:
key_length (
int) – Length of ECC key in bytes- Return type:
- Returns:
Corresponding ECC curve type
- Raises:
SPSDKError – When key length doesn’t correspond to any supported curve
- spsdk.crypto.keys.get_supported_keys_generators(basic=False)#
Get supported key generators dictionary.
Returns a dictionary mapping key type names to their corresponding generator functions and parameters. Supports RSA, ECC, and optionally SM2, Dilithium, and ML-DSA key types based on system capabilities.
- Parameters:
basic (
bool) – If True, return only RSA and ECC key generators, defaults to False- Return type:
dict[str,tuple[Callable[...,PrivateKey],dict[str,Union[int,str,bool]]]]- Returns:
Dictionary mapping key type names to tuples of (generator_function, parameters)
- spsdk.crypto.keys.prompt_for_passphrase()#
Prompt interactively for private key passphrase.
This function displays a secure password prompt to the user and waits for input. The entered passphrase is hidden from display for security purposes.
- Raises:
SPSDKError – When interactive mode is disabled via SPSDK_INTERACTIVE_DISABLED environment variable.
- Return type:
str- Returns:
The passphrase entered by the user.
Crypto module certificate generation#
SPSDK Certificate management utilities.
This module provides comprehensive functionality for X.509 certificate handling, including certificate generation, validation, chain verification, and specialized support for WPC Qi authentication certificates within the SPSDK framework.
- class spsdk.crypto.certificate.Certificate(certificate)#
Bases:
BaseClassSPSDK Certificate wrapper for X.509 certificates.
This class provides a unified interface for working with X.509 certificates in SPSDK operations, including certificate generation, validation, and cryptographic operations across NXP MCU portfolio.
Initialize SPSDK Certificate wrapper.
Creates a new SPSDK Certificate instance from a cryptography library Certificate object.
- Parameters:
certificate (
Certificate) – Cryptography Certificate representation to wrap.- Raises:
AssertionError – If certificate is not an instance of x509.Certificate.
- property ca: bool#
Check if CA flag is set in certificate.
The method examines the Basic Constraints extension to determine if the certificate has Certificate Authority capabilities.
- Returns:
True if CA flag is set, False otherwise.
- export(encoding=<SPSDKEncoding.NXP: 'NXP'>)#
Export certificate to bytes in specified encoding format.
The method supports multiple encoding formats including NXP-specific format which uses DER encoding aligned to 4-byte boundaries with zero padding.
- Parameters:
encoding (
SPSDKEncoding) – The encoding format to use for export (defaults to NXP format).- Return type:
bytes- Returns:
Certificate data as bytes in the specified encoding format.
- property extensions: Extensions#
Get certificate extensions.
Returns an Extensions object containing all X.509 certificate extensions such as key usage, subject alternative names, and other certificate attributes.
- Returns:
Extensions object with certificate extension data.
- static generate_certificate(subject, issuer, subject_public_key, issuer_private_key, serial_number=None, duration=None, extensions=None, pss_padding=None)#
Generate X.509 certificate with specified parameters.
Creates a new X.509 certificate using the provided subject and issuer information, with configurable validity period, extensions, and RSA padding options.
- Parameters:
subject (
Name) – Subject name that the CA issues the certificate to.issuer (
Name) – Issuer name that issued the certificate.subject_public_key (
PublicKey) – Public key of the certificate subject.issuer_private_key (
PrivateKey) – Private key of the certificate issuer for signing.serial_number (
Optional[int]) – Certificate serial number, random if not specified.duration (
Optional[int]) – Certificate validity period in days, defaults to very long period.extensions (
Optional[list[ExtensionType]]) – List of X.509 extensions to include in the certificate.pss_padding (
Optional[bool]) – Use RSA-PSS padding instead of PKCS1v15, RSA keys only.
- Return type:
- Returns:
Generated X.509 certificate instance.
- get_public_key()#
Get public key from certificate.
Extracts the public key from the certificate using the standard method, and falls back to manual extraction if the standard method fails.
- Return type:
- Returns:
Public key extracted from the certificate.
- property issuer: Name#
Get the certificate issuer name.
Returns the issuer name object containing the distinguished name information of the certificate authority that issued this certificate.
- Returns:
Certificate issuer name object.
- classmethod load(file_path)#
Load the Certificate from the given file.
- Parameters:
file_path (
str) – Path to the file where the certificate is stored.- Return type:
Self- Returns:
Certificate instance loaded from the file.
- property not_valid_after: datetime#
Get the certificate’s expiration date and time.
Returns the ‘not valid after’ timestamp from the X.509 certificate, indicating when the certificate expires. The datetime is always in UTC.
- Returns:
Certificate expiration datetime in UTC timezone.
- property not_valid_before: datetime#
Get the certificate’s not-valid-before timestamp.
Returns the earliest date and time when the certificate becomes valid, represented as a UTC datetime object.
- Returns:
Certificate’s not-valid-before time as UTC datetime.
- classmethod parse(data)#
Parse X.509 certificate from bytes array.
The method automatically detects the certificate encoding (PEM or DER) and handles padded DER certificates by removing trailing null bytes if necessary.
- Parameters:
data (
bytes) – Certificate data in PEM or DER format.- Return type:
Self- Returns:
Parsed certificate object.
- Raises:
SPSDKError – Cannot load certificate due to invalid format or data.
SPSDKValueError – Invalid certificate data structure.
- public_key_hash(algorithm=EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'))#
Get public key hash.
Computes hash of the certificate’s public key using the specified hash algorithm.
- Parameters:
algorithm (
EnumHashAlgorithm) – Hash algorithm to use for computing the key hash, defaults to SHA256.- Return type:
bytes- Returns:
Hash of the public key as bytes.
- property raw_size: int#
Get raw size of the certificate in bytes.
- Returns:
Size of the certificate in bytes.
- save(file_path, encoding_type=<SPSDKEncoding.PEM: 'PEM'>)#
Save the certificate/CSR into file.
- Parameters:
file_path (
str) – Path to the file where certificate/CSR will be stored.encoding_type (
SPSDKEncoding) – Encoding type for the output file (PEM or DER).
- Raises:
SPSDKError – If file cannot be written or export fails.
- Return type:
None
- property self_signed: bool#
Check if the certificate is self-signed.
A certificate is considered self-signed when it can be validated using its own public key, meaning the certificate was signed by the same entity that it represents.
- Returns:
True if the certificate is self-signed, False otherwise.
- property serial_number: int#
Get certificate serial number.
- Returns:
Serial number of the certificate.
- property signature: bytes#
Get the signature bytes from the certificate.
- Returns:
The signature bytes of the certificate.
- property signature_algorithm_oid: ObjectIdentifier#
Get the ObjectIdentifier of the signature algorithm.
- Returns:
Object identifier representing the signature algorithm used to sign this certificate.
- property signature_hash_algorithm: HashAlgorithm | None#
Get signature hash algorithm from certificate.
Returns the hash algorithm used for signing the certificate digest. This method handles unsupported algorithms gracefully by returning None.
- Returns:
Hash algorithm instance if supported, None if algorithm is unsupported.
- property subject: Name#
Get the subject name object from the certificate.
- Returns:
Subject name object containing certificate subject information.
- property tbs_certificate_bytes: bytes#
Get the tbsCertificate payload bytes as defined in RFC 5280.
The tbsCertificate (to-be-signed certificate) contains the certificate data that is signed by the certificate authority.
- Returns:
Raw bytes of the tbsCertificate structure.
- validate(issuer_certificate)#
Validate certificate against its issuer.
The method verifies the certificate’s signature using the issuer’s public key and the certificate’s signature hash algorithm.
- Parameters:
issuer_certificate (
Certificate) – Issuer’s certificate used for validation.- Raises:
SPSDKError – Signature hash algorithm is unknown or unsupported key type.
- Return type:
bool- Returns:
True if certificate is valid, False otherwise.
- validate_subject(subject_certificate)#
Validate subject certificate against this certificate.
This method verifies the digital signature of the subject certificate using the public key from this certificate, confirming the certificate chain validity.
- Parameters:
subject_certificate (
Certificate) – The certificate to be validated against this certificate.- Raises:
SPSDKError – Unknown subject certificate’s signature hash algorithm.
- Return type:
bool- Returns:
True if the certificate signature is valid, False otherwise.
- property version: Version#
Get the certificate version.
- Returns:
Certificate version information.
- exception spsdk.crypto.certificate.SPSDKExtensionNotFoundError(desc=None)#
Bases:
SPSDKError,ExtensionNotFoundSPSDK extension not found error.
Custom exception raised when a required X.509 certificate extension is not found during certificate processing or validation operations.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- class spsdk.crypto.certificate.WPCQiAuthPolicy(value)#
Bases:
UnrecognizedExtensionWPC Qi Auth Policy x509 extension.
This class represents a Wireless Power Consortium (WPC) Qi authentication policy extension for X.509 certificates, implementing the standardized OID for Qi wireless charging authentication mechanisms.
- Variables:
oid – Object identifier for WPC Qi Auth Policy extension (2.23.148.1.1).
Initialize the extension with given policy number.
- Parameters:
value (
int) – Policy number to be encoded in the extension.- Raises:
ValueError – If value cannot be converted to 4-byte big-endian format.
- oid: typing.ClassVar[ObjectIdentifier] = <ObjectIdentifier(oid=2.23.148.1.1, name=Unknown OID)>#
- class spsdk.crypto.certificate.WPCQiAuthRSID(value)#
Bases:
UnrecognizedExtensionWPC Qi Auth RSID x509 extension.
This class represents a Wireless Power Consortium (WPC) Qi Authentication Receiver System Identifier (RSID) as an X.509 certificate extension. It encapsulates the RSID value in the proper ASN.1 format for certificate embedding.
- Variables:
oid – Object Identifier for WPC Qi Auth RSID extension (2.23.148.1.2).
Initialize the extension with given RSID in form of a hex-string.
- Parameters:
value (
str) – RSID value as hexadecimal string to be used in the extension.- Raises:
ValueError – If the hex string cannot be converted to bytes.
- oid: typing.ClassVar[ObjectIdentifier] = <ObjectIdentifier(oid=2.23.148.1.2, name=Unknown OID)>#
- spsdk.crypto.certificate.generate_extensions(config)#
Generate X.509 certificate extensions from configuration data.
This method processes configuration dictionary and creates corresponding X.509 extensions including Basic Constraints, WPC QiAuth Policy, and WPC QiAuth RSID extensions.
- Parameters:
config (
dict) – Dictionary containing extension configuration data with keys like ‘BASIC_CONSTRAINTS’, ‘WPC_QIAUTH_POLICY’, ‘WPC_QIAUTH_RSID’- Return type:
list[ExtensionType]- Returns:
List of X.509 extension objects ready for certificate creation
- spsdk.crypto.certificate.generate_name(config)#
Generate X.509 Name object from configuration.
The method creates an X.509 Name object by processing the provided configuration which can be either a dictionary or list format. It handles multiple values for the same attribute and validates all attribute names against SPSDKNameOID.
- Parameters:
config (
Union[list[dict[str,str]],dict[str,Union[str,list[str]]]]) – Configuration for X.509 name attributes in dictionary or list format.- Raises:
SPSDKError – Invalid certificate attribute name provided.
- Return type:
Name- Returns:
X.509 Name object with configured attributes.
- spsdk.crypto.certificate.validate_ca_flag_in_cert_chain(chain_list)#
Validate CA flag in certification chain.
Checks whether the CA (Certificate Authority) flag is set in the first certificate of the provided certificate chain.
- Parameters:
chain_list (
list[Certificate]) – List of Certificate objects representing the certificate chain.- Return type:
bool- Returns:
True if CA flag is set in the first certificate, False otherwise.
- spsdk.crypto.certificate.validate_certificate_chain(chain_list)#
Validate chain of certificates.
Validates each certificate in the chain against its issuer certificate. Each certificate is verified using the public key of the next certificate in the chain (which should be its issuer).
- Parameters:
chain_list (
list[Certificate]) – List of certificates in chain, ordered from leaf to root.- Return type:
list[bool]- Returns:
List of boolean values indicating validation result for each certificate pair.
- Raises:
SPSDKError – When chain has less than two certificates.
Crypto module symmetric encryption/decryption#
SPSDK symmetric cryptography utilities.
This module provides a comprehensive set of functions for symmetric encryption and decryption operations using various AES modes and SM4 algorithm. It includes support for key wrapping, block cipher modes (ECB, CBC, CTR, XTS), and authenticated encryption modes (CCM, GCM).
- class spsdk.crypto.symmetric.Counter(nonce, ctr_value=None, ctr_byteorder_encoding=Endianness.LITTLE)#
Bases:
objectAES counter with specified counter byte ordering and customizable increment.
This class manages a 16-byte counter for AES encryption operations, providing control over byte ordering and counter incrementation. The counter consists of a 12-byte nonce and a 4-byte counter value that can be incremented as needed.
Initialize AES counter mode cipher.
Initializes the counter mode cipher with a 16-byte nonce where the last four bytes serve as the initial counter value. The counter can be further adjusted with an additional offset value.
- Parameters:
nonce (
bytes) – 16-byte nonce where last four bytes are used as initial counter valuectr_value (
Optional[int]) – Optional counter offset added to the counter value from noncectr_byteorder_encoding (
Endianness) – Byte order encoding for counter value conversion
- Raises:
SPSDKError – When nonce is not exactly 16 bytes long
- increment(value=1)#
Increment counter by specified value.
- Parameters:
value (
int) – Value to add to counter.- Return type:
None
- property value: bytes#
Get the initial vector for AES encryption.
Combines the nonce with the counter value to create the complete initialization vector used for AES encryption operations.
- Returns:
Complete initialization vector as bytes combining nonce and counter.
- spsdk.crypto.symmetric.aes_cbc_decrypt(key, encrypted_data, iv_data=None)#
Decrypt encrypted data with AES in CBC mode.
The function performs AES decryption using Cipher Block Chaining (CBC) mode with optional initialization vector. If no IV is provided, a zero-filled IV is used.
- Parameters:
key (
bytes) – The AES key for data decryption (must be valid AES key length).encrypted_data (
bytes) – The encrypted input data to be decrypted.iv_data (
Optional[bytes]) – Initialization vector data (optional, defaults to zero-filled).
- Raises:
SPSDKError – Invalid key length or initialization vector length.
- Return type:
bytes- Returns:
Decrypted data as bytes.
- spsdk.crypto.symmetric.aes_cbc_encrypt(key, plain_data, iv_data=None)#
Encrypt plain data with AES in CBC mode.
The function performs AES encryption using Cipher Block Chaining (CBC) mode with PKCS7 padding. If no initialization vector is provided, a zero-filled IV is used.
- Parameters:
key (
bytes) – AES encryption key, must be valid AES key length (128, 192, or 256 bits).plain_data (
bytes) – Raw data to be encrypted.iv_data (
Optional[bytes]) – Initialization vector for CBC mode, defaults to zero-filled block.
- Raises:
SPSDKError – Invalid key length or IV length.
- Return type:
bytes- Returns:
Encrypted data with PKCS7 padding applied.
- spsdk.crypto.symmetric.aes_ccm_decrypt(key, encrypted_data, nonce, associated_data, tag_len=16)#
Decrypt data using AES in CCM mode (Counter with CBC-MAC).
AES-CCM provides both confidentiality and authenticity for the encrypted data. The method decrypts the input data and verifies the authentication tag.
- Parameters:
key (
bytes) – AES key for decryption (16, 24, or 32 bytes).encrypted_data (
bytes) – Data to be decrypted including authentication tag.nonce (
bytes) – Nonce value for CCM mode (7-13 bytes).associated_data (
bytes) – Additional authenticated data (not encrypted).tag_len (
int) – Authentication tag length in bytes (default 16).
- Raises:
InvalidTag – If authentication verification fails.
ValueError – If key, nonce, or tag length is invalid.
- Return type:
bytes- Returns:
Decrypted plaintext 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-MAC).
AES-CCM provides both confidentiality and authenticity for the encrypted data. The method combines the plaintext with associated data for authentication.
- Parameters:
key (
bytes) – The encryption key for AES algorithm.plain_data (
bytes) – Input data to be encrypted.nonce (
bytes) – Nonce value used for counter initialization.associated_data (
bytes) – Additional data for authentication (not encrypted).tag_len (
int) – Length of the authentication tag in bytes.
- Return type:
bytes- Returns:
Encrypted data with authentication tag appended.
- spsdk.crypto.symmetric.aes_ctr_decrypt(key, encrypted_data, nonce)#
Decrypt data using AES algorithm in CTR mode.
This function performs AES decryption in Counter (CTR) mode, which is a stream cipher mode that turns a block cipher into a stream cipher by repeatedly encrypting successive values of a counter.
- Parameters:
key (
bytes) – AES encryption key (must be 16, 24, or 32 bytes for AES-128/192/256).encrypted_data (
bytes) – The encrypted data to be decrypted.nonce (
bytes) – Nonce value with counter for CTR mode (typically 16 bytes for AES).
- Return type:
bytes- Returns:
Decrypted plaintext data as bytes.
- spsdk.crypto.symmetric.aes_ctr_encrypt(key, plain_data, nonce)#
Encrypt plain data with AES in CTR mode.
- Parameters:
key (
bytes) – The encryption key in bytes format.plain_data (
bytes) – Input data to be encrypted.nonce (
bytes) – Nonce data with counter value for CTR mode.
- Return type:
bytes- Returns:
Encrypted data in bytes format.
- spsdk.crypto.symmetric.aes_ecb_decrypt(key, encrypted_data)#
Decrypt encrypted data with AES in ECB mode.
- Parameters:
key (
bytes) – The AES encryption key used for data decryption.encrypted_data (
bytes) – The encrypted input data to be decrypted.
- Return type:
bytes- Returns:
Decrypted data as bytes.
- spsdk.crypto.symmetric.aes_ecb_encrypt(key, plain_data)#
Encrypt plain data with AES in ECB mode.
- Parameters:
key (
bytes) – The encryption key in bytes format.plain_data (
bytes) – Input data to be encrypted.
- Return type:
bytes- Returns:
Encrypted data in bytes format.
- spsdk.crypto.symmetric.aes_gcm_decrypt(key, encrypted_data, init_vector, associated_data=b'')#
Decrypt encrypted data with AES in GCM mode (Galois/Counter Mode).
The method decrypts data that was encrypted using AES-GCM algorithm. The encrypted data must include the authentication tag appended at the end. The method validates the key length and initialization vector before performing decryption.
- Parameters:
key (
bytes) – The key for data decryption (16, 24, or 32 bytes for AES-128/192/256)encrypted_data (
bytes) – Input data with authentication tag appendedinit_vector (
bytes) – Initialization vector (nonce) - must be exactly 12 bytesassociated_data (
bytes) – Associated data - unencrypted but authenticated data
- Return type:
bytes- Returns:
Decrypted data as bytes
- Raises:
SPSDKError – Invalid key length, IV length, or authentication failure
- spsdk.crypto.symmetric.aes_gcm_encrypt(key, plain_data, init_vector=None, associated_data=b'')#
Encrypt plain data with AES in GCM mode (Galois/Counter Mode).
The method uses AES-GCM encryption which provides both confidentiality and authenticity. The authentication tag is automatically appended to the encrypted data.
- Parameters:
key (
bytes) – The AES encryption key (must be 128, 192, or 256 bits).plain_data (
bytes) – Input data to be encrypted.init_vector (
Optional[bytes]) – Initialization vector (nonce), defaults to 12 zero bytes if None.associated_data (
bytes) – Additional authenticated data that remains unencrypted.
- Return type:
bytes- Returns:
Encrypted data with authentication tag appended.
- Raises:
SPSDKError – Invalid key length or initialization vector length.
- spsdk.crypto.symmetric.aes_key_unwrap(kek, wrapped_key)#
Unwrap a key using AES key wrapping algorithm with key-encrypting key (KEK).
This method implements the AES key unwrapping algorithm as defined in RFC 3394 to securely unwrap a previously wrapped cryptographic key.
- Parameters:
kek (
bytes) – The key-encrypting key used for unwrapping.wrapped_key (
bytes) – The wrapped key data to be unwrapped.
- Return type:
bytes- Returns:
The unwrapped key as bytes.
- spsdk.crypto.symmetric.aes_key_wrap(kek, key_to_wrap)#
Wrap a key using AES key wrapping algorithm with a key-encrypting key (KEK).
This function implements the AES key wrap algorithm as defined in RFC 3394, which provides a secure method for encrypting cryptographic keys using another key.
- Parameters:
kek (
bytes) – The key-encrypting key used to wrap the target key.key_to_wrap (
bytes) – The cryptographic key data to be wrapped.
- Return type:
bytes- Returns:
The wrapped key as bytes.
- spsdk.crypto.symmetric.aes_xts_decrypt(key, encrypted_data, tweak)#
Decrypt encrypted data with AES in XTS mode.
The XTS mode is designed for encrypting data on storage devices where the same plaintext is encrypted to different ciphertext based on its logical position.
- Parameters:
key (
bytes) – The encryption key used for AES decryption.encrypted_data (
bytes) – The encrypted data to be decrypted.tweak (
bytes) – The 16-byte tweak value used in XTS mode for sector addressing.
- Return type:
bytes- Returns:
Decrypted plaintext data.
- spsdk.crypto.symmetric.aes_xts_encrypt(key, plain_data, tweak)#
Encrypt plain data with AES in XTS mode.
The XTS mode is designed for encrypting data on storage devices where the same plaintext might be encrypted multiple times with different tweaks.
- Parameters:
key (
bytes) – The encryption key (must be 32 or 64 bytes for AES-128 or AES-256).plain_data (
bytes) – Input data to be encrypted.tweak (
bytes) – The tweak value (must be exactly 16 bytes).
- 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 decryption.encrypted_data (
bytes) – Input data to be decrypted.iv_data (
Optional[bytes]) – Initialization vector data, defaults to zero-filled block if None.
- Raises:
SPSDKError – Invalid key length or initialization vector length.
- Return type:
bytes- Returns:
Decrypted data.
- spsdk.crypto.symmetric.sm4_cbc_encrypt(key, plain_data, iv_data=None)#
Encrypt plain data with SM4 in CBC mode.
The method encrypts input data using SM4 algorithm in CBC (Cipher Block Chaining) mode. If no initialization vector is provided, a zero-filled IV is used. Input data is automatically padded to block size alignment.
- Parameters:
key (
bytes) – The key for SM4 encryption, must be valid SM4 key length.plain_data (
bytes) – Input data to be encrypted.iv_data (
Optional[bytes]) – Initialization vector data, defaults to zero-filled if None.
- Raises:
SPSDKError – Invalid key length or IV length.
- Return type:
bytes- Returns:
Encrypted data.
Crypto module CMS#
SPSDK CMS (Cryptographic Message Syntax) signature utilities.
This module provides functionality for creating and handling CMS signature containers using ASN1Crypto implementation. It supports data signing operations with X.509 certificates and various hash algorithms for secure message authentication.
- spsdk.crypto.cms.cms_sign(zulu, data, certificate, signing_key, signature_provider)#
Sign provided data and return CMS signature.
Creates a CMS (Cryptographic Message Syntax) signature for the provided data using either a private key or signature provider along with the certificate information.
- Parameters:
zulu (
datetime) – Current UTC time and date for signature timestamp.data (
bytes) – Binary data to be signed.certificate (
Certificate) – Certificate containing issuer information for signature.signing_key (
Optional[PrivateKey]) – Private key for signing, mutually exclusive with signature_provider.signature_provider (
Optional[SignatureProvider]) – External signature provider, mutually exclusive with signing_key.
- Return type:
bytes- Returns:
CMS signature in binary format.
- Raises:
SPSDKValueError – If certificate is not present.
SPSDKValueError – If neither private key nor signature provider is present.
SPSDKValueError – If both private key and signature provider are specified.
SPSDKTypeError – If unsupported private key type is provided.
SPSDKError – If incorrect time-zone is specified.
- spsdk.crypto.cms.sign_data(data_to_sign, signing_key, signature_provider)#
Sign the data using either a private key or signature provider.
The method supports both direct signing with a private key and signing through a signature provider. For ECC keys, the signature is automatically converted to DER format when needed.
- Parameters:
data_to_sign (
bytes) – Data to be signed as bytes.signing_key (
Optional[PrivateKey]) – Private key for signing, mutually exclusive with signature_provider parameter.signature_provider (
Optional[SignatureProvider]) – External signature provider, mutually exclusive with signing_key parameter.
- Raises:
SPSDKValueError – When both signing_key and signature_provider are provided, or when neither is provided.
- Return type:
bytes- Returns:
Digital signature as bytes in appropriate format.
Crypto module CMAC#
SPSDK CMAC (Cipher-based Message Authentication Code) implementation.
This module provides cryptographic functions for generating and validating CMAC authentication codes using AES encryption for secure packet authentication in SPSDK applications.
- spsdk.crypto.cmac.cmac(key, data)#
Compute CMAC (Cipher-based Message Authentication Code) for given data.
Uses AES algorithm to generate a cryptographic message authentication code that provides both data integrity and authenticity verification.
- Parameters:
key (
bytes) – AES encryption key in bytes formatdata (
bytes) – Input data to be authenticated in bytes format
- Return type:
bytes- Returns:
CMAC authentication code as bytes
- spsdk.crypto.cmac.cmac_validate(key, data, signature)#
Validate CMAC signature against provided data using specified key.
The method uses AES algorithm to compute CMAC and verifies it against the provided signature.
- Parameters:
key (
bytes) – The key in bytes format for CMAC computationdata (
bytes) – Input data in bytes format to be validatedsignature (
bytes) – CMAC signature in bytes format to validate against
- Raises:
InvalidSignature – When signature validation fails
- Return type:
bool- Returns:
True if signature is valid, False otherwise
Crypto module HMAC#
SPSDK HMAC authentication utilities.
This module provides HMAC (Hash-based Message Authentication Code) functionality for packet authentication and validation using cryptographic hash algorithms.
- spsdk.crypto.spsdk_hmac.hmac(key, data, algorithm=EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'))#
Compute HMAC from data with specified key and algorithm.
The method generates Hash-based Message Authentication Code using the provided key, data, and hash algorithm. Supports various hash algorithms including SHA256, SHA384, and SHA512.
- Parameters:
key (
bytes) – The cryptographic key in bytes format.data (
bytes) – Input data to be authenticated in bytes format.algorithm (
EnumHashAlgorithm) – Hash algorithm type for HMAC computation, defaults to SHA256.
- Return type:
bytes- Returns:
HMAC digest as bytes.
- spsdk.crypto.spsdk_hmac.hmac_validate(key, data, signature, algorithm=EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'))#
Validate HMAC signature against provided data using specified key and algorithm.
- Parameters:
key (
bytes) – The key in bytes format used for HMAC generation.data (
bytes) – Input data in bytes format to validate against signature.signature (
bytes) – HMAC signature in bytes format to validate.algorithm (
EnumHashAlgorithm) – Algorithm type for HASH function (sha256, sha384, sha512, …).
- Return type:
bool- Returns:
True if signature is valid, False otherwise.
Crypto module hash#
SPSDK cryptographic hash algorithms implementation.
This module provides a unified interface for various hash algorithms used across SPSDK, including SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. It offers enumeration of supported algorithms, hash computation utilities, and algorithm metadata retrieval functions.
- class spsdk.crypto.hash.EnumHashAlgorithm(tag, label, description=None)#
Bases:
SpsdkEnumHash algorithm enumeration for cryptographic operations.
This enumeration defines supported hash algorithms used across SPSDK for cryptographic operations including signing, verification, and data integrity checks. Each algorithm is represented with its numeric identifier, string representation, and display name.
- MD5 = (4, 'md5', 'MD5')#
- NONE = (254, 'none', 'NONE')#
- SHA1 = (0, 'sha1', 'SHA1')#
- SHA224 = (11, 'sha224', 'SHA224')#
- SHA256 = (1, 'sha256', 'SHA256')#
- SHA384 = (2, 'sha384', 'SHA384')#
- SHA3_256 = (6, 'sha3_256', 'SHA3_256')#
- SHA3_384 = (7, 'sha3_384', 'SHA3_384')#
- SHA3_512 = (8, 'sha3_512', 'SHA3_512')#
- SHA512 = (3, 'sha512', 'SHA512')#
- SHAKE_128_256 = (9, 'shake_128_256', 'SHAKE128 with 256b output')#
- SHAKE_256_512 = (10, 'shake_256_512', 'SHAKE256 with 512b output')#
- SM3 = (5, 'sm3', 'SM3')#
- class spsdk.crypto.hash.Hash(algorithm=EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'))#
Bases:
objectSPSDK Hash computation wrapper.
This class provides a unified interface for cryptographic hash operations across different hash algorithms. It wraps the underlying cryptographic library to offer consistent hash computation functionality with support for incremental data processing and various data types.
Initialize hash object.
- Parameters:
algorithm (
EnumHashAlgorithm) – Algorithm type enum, defaults to EnumHashAlgorithm.SHA256
- finalize()#
Finalize the hash computation and return the digest.
This method completes the hash computation process and returns the final hash digest. After calling this method, the hash object cannot be used for further updates.
- Return type:
bytes- Returns:
The computed hash digest as bytes.
- update(data)#
Update the hash object with new data.
- Parameters:
data (
bytes) – Binary data to be added to the hash calculation.- Return type:
None
- update_int(value)#
Update the hash by new integer value as is.
The method converts the absolute value of the integer to bytes using big-endian byte order and updates the hash with the resulting byte data.
- Parameters:
value (
int) – Integer value to be hashed (absolute value will be used).- Return type:
None
- spsdk.crypto.hash.get_hash(data, algorithm=EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'))#
Compute hash digest from input data using specified algorithm.
- Parameters:
data (
bytes) – Input data to be hashed.algorithm (
EnumHashAlgorithm) – Hash algorithm to use for computation.
- Raises:
SPSDKError – If the specified algorithm is not supported.
- Return type:
bytes- Returns:
Hash digest as bytes.
- spsdk.crypto.hash.get_hash_algorithm(algorithm)#
Get hash algorithm instance for specified algorithm type.
The method handles special cases for SHAKE algorithms with predefined digest sizes and uses dynamic class lookup for standard hash algorithms.
- Parameters:
algorithm (
EnumHashAlgorithm) – Hash algorithm type enumeration value.- Raises:
SPSDKError – If the specified algorithm is not supported.
- Return type:
HashAlgorithm- Returns:
Instance of the corresponding hash algorithm class.
- spsdk.crypto.hash.get_hash_length(algorithm)#
Get hash algorithm binary length.
Returns the digest size in bytes for the specified hash algorithm.
- Parameters:
algorithm (
EnumHashAlgorithm) – Hash algorithm type enumeration.- Return type:
int- Returns:
Length of hash digest in bytes.
- Raises:
SPSDKError – If algorithm is not supported or found.
Crypto module utils#
SPSDK cryptographic utilities and helper functions.
This module provides essential cryptographic utility functions for key management, certificate handling, and cryptographic operations across the SPSDK framework. It includes functionality for key generation, public key extraction, signature validation, and cryptographic type conversions.
- spsdk.crypto.utils.extract_public_key(file_path, password=None, search_paths=None)#
Extract any kind of public key from a file.
The method supports files containing Certificate, Private Key or Public Key formats. It can search for the file in multiple directories and handle password-protected files.
- 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 cannot 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 data containing Certificate, Private Key or Public Key.
The method attempts to parse the input data as a certificate first, then as a private key, and finally as a public key. For CA certificates, the returned public key will have the ‘ca’ attribute set to True.
- Parameters:
object_data (
bytes) – Raw data containing certificate, private key, or public key.password (
Optional[str]) – Optional password for encrypted private keys.
- Raises:
SPSDKError – Raised when data cannot be parsed as any supported key format.
- Return type:
- Returns:
Extracted public key of any supported type.
- spsdk.crypto.utils.extract_public_keys(secret_files, password=None, search_paths=None)#
Extract public keys from multiple files containing certificates, private keys, or public keys.
This method processes multiple input files and extracts the public key component from each, regardless of whether the source file contains a certificate, private key, or public key.
- Parameters:
secret_files (
Iterable[str]) – Iterable of file paths to process for public key extraction.password (
Optional[str]) – Password for encrypted private key files, defaults to None.search_paths (
Optional[list[str]]) – Additional directories to search for files, defaults to None.
- Return type:
list[PublicKey]- Returns:
List of extracted public keys from all processed files.
- spsdk.crypto.utils.generate_img_csf_key(key_type, encoding, keys_path, crts_path, ca_issuer, srk_private_key, duration, idx, password, serial=None, print_func=<built-in function print>, start_idx=0, key_postfix=None)#
Generate IMG and CSF keys and certificates.
This function creates both IMG (Image) and CSF (Command Sequence File) key pairs and their corresponding certificates signed by the provided SRK private key. The certificates are saved to the specified paths with the given encoding format.
- Parameters:
key_type (
str) – Type of cryptographic key to generate (e.g., ‘rsa2048’, ‘ecc256’).encoding (
str) – Encoding format for keys and certificates (‘DER’ or ‘PEM’).keys_path (
str) – Directory path where generated private keys will be stored.crts_path (
str) – Directory path where generated certificates will be stored.ca_issuer (
Name) – Certificate authority issuer name for the generated certificates.srk_private_key (
PrivateKey) – SRK (Super Root Key) private key used to sign the certificates.duration (
int) – Validity period of the certificates in years.idx (
int) – Index number used for naming the generated keys and certificates.password (
str) – Password used to protect the generated private keys.serial (
Optional[list[int]]) – List of serial numbers for certificates. Must have at least idx+1 items.print_func (
Callable[[str],None]) – Function used for output messages, defaults to built-in print.start_idx (
int) – Starting index offset for key numbering, defaults to 0.key_postfix (
Optional[str]) – Optional suffix appended to key names, defaults to None.
- Raises:
SPSDKError – If serial list is provided but has insufficient items for the index.
- Return type:
None
- spsdk.crypto.utils.generate_key_pair(key_type, encoding, keys_path, key_prefix, idx, is_ca, password, print_func=<built-in function print>, key_postfix=None)#
Generate key pair with the naming convention.
The method creates a cryptographic key pair using specified parameters and saves both private and public keys to the filesystem with standardized naming convention.
- Parameters:
key_type (
str) – Key type from get_supported_keys_generators().encoding (
str) – Key encoding format (DER or PEM).keys_path (
str) – Path to the directory where keys will be stored.key_prefix (
str) – Prefix for the key filename (e.g., ‘CA’).idx (
int) – Index number to append to the key name.is_ca (
bool) – True if the certificate with this key is certificate authority.password (
str) – Password to protect the private key.print_func (
Callable[[str],None]) – Custom function to print status messages, defaults to print.key_postfix (
Optional[str]) – Optional postfix to append to the key name, defaults to None.
- Return type:
tuple[PrivateKey,PublicKey,str,str]- Returns:
Tuple of private key, public key, key name and certificate name.
- spsdk.crypto.utils.generate_srk_keys(key_type, encoding, keys_path, crts_path, ca_issuer, ca_private_key, duration, srk_is_ca, password, keys_number, serial=None, print_func=<built-in function print>, start_idx=0, use_img_csf=False)#
Generate SRK keys and certificates.
This function generates Super Root Key (SRK) pairs and their corresponding certificates signed by a CA. Optionally generates SGK certificates or IMG/CSF certificates based on configuration.
- Parameters:
key_type (
str) – Type of cryptographic key to generate (e.g., ‘rsa2048’, ‘ecc256’).encoding (
str) – Encoding format for keys and certificates (‘DER’ or ‘PEM’).keys_path (
str) – Directory path where generated private keys will be stored.crts_path (
str) – Directory path where generated certificates will be stored.ca_issuer (
Name) – Certificate Authority issuer name for signing certificates.ca_private_key (
PrivateKey) – CA private key used to sign the generated certificates.duration (
int) – Certificate validity duration in years.srk_is_ca (
bool) – Whether the SRK should be marked as a Certificate Authority.password (
str) – Password for protecting the generated private keys.keys_number (
int) – Number of SRK key pairs to generate.serial (
Optional[list[int]]) – List of serial numbers for certificates, defaults to None.print_func (
Callable[[str],None]) – Function for output messages, defaults to print.start_idx (
int) – Starting index for key numbering, defaults to 0.use_img_csf (
bool) – Whether to generate IMG and CSF certificates instead of SGK, defaults to False.
- Raises:
SPSDKError – If serial numbers list length doesn’t match keys_number.
- Return type:
None
- spsdk.crypto.utils.get_hash_type_from_signature_size(signature_size)#
Return hash type from ECC signature size.
Determines the appropriate hash algorithm based on the size of an ECC signature. Supports standard ECC signature sizes for SHA256, SHA384, and SHA512.
- Parameters:
signature_size (
int) – Size of the ECC signature in bytes.- Raises:
SPSDKValueError – Unknown or unsupported signature size.
- Return type:
- Returns:
Hash algorithm enum corresponding to the signature size.
- spsdk.crypto.utils.get_matching_key_id(public_keys, signature_provider)#
Get index of public key that matches the given private key.
The method iterates through the list of public keys and uses the signature provider to verify which public key corresponds to the private key held by the signature provider.
- Parameters:
public_keys (
list[PublicKey]) – List of public keys 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 between private key and any public key in the list.
- Return type:
int- Returns:
Index of the matching public key in the provided list.
- spsdk.crypto.utils.get_matching_key_id_from_signature(public_keys, signed_data, signature, algorithm=None, **kwargs)#
Get index of public key that matches given signed data and signature.
The method iterates through the provided public keys and verifies which one can successfully validate the given signature against the signed data.
- Parameters:
public_keys (
list[PublicKey]) – List of public keys to search for matching private key.signed_data (
bytes) – The data that was signed.signature (
bytes) – The signature to verify against the signed data.algorithm (
Optional[EnumHashAlgorithm]) – Hash algorithm to use for verification, None for auto-detection.kwargs (
Any) – Additional keyword arguments for specific key types.
- Raises:
SPSDKValueError – When no matching public key is found.
- Return type:
int- Returns:
Index of the matching public key in the provided list.
Interface for all potential signature providers#
SPSDK signature provider interface and implementations.
This module provides a unified interface for various signature providers used in SPSDK, including file-based, interactive, and HTTP proxy signature providers. It enables flexible signature generation across different deployment scenarios from development to production environments.
- class spsdk.crypto.signature_provider.InteractivePlainFileSP(file_path, hash_alg=None, search_paths=None, **kwargs)#
Bases:
PlainFileSPInteractive signature provider for encrypted private key files.
This signature provider extends PlainFileSP to handle encrypted private keys by automatically prompting the user for a password when the key requires decryption. It provides a seamless interactive experience for signature operations with password-protected keys.
- Variables:
identifier – Provider identifier for registration and lookup.
Initialize the interactive plain file signature provider.
This provider automatically prompts for password if the private key file requires one and no password was provided in the initial attempt.
- Parameters:
file_path (
str) – Path to private key file.hash_alg (
Optional[EnumHashAlgorithm]) – Hash algorithm for the signature, defaults to sha256.search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None.kwargs (
Union[str,int,bool]) – Additional keyword arguments including optional password.
- Raises:
SPSDKError – Invalid private key or initialization failure.
-
identifier:
str= 'interactive_file'#
- class spsdk.crypto.signature_provider.PlainFileSP(file_path, password=None, hash_alg=None, search_paths=None, **kwargs)#
Bases:
SignatureProviderFile-based signature provider for local cryptographic operations.
This signature provider implementation loads private keys from local files and performs cryptographic signing operations. It supports encrypted private keys with password protection and automatic hash algorithm selection based on key type and size.
- Variables:
identifier – Provider identifier used for configuration and registration.
Initialize the plain file signature provider.
- Parameters:
file_path (
str) – Path to private key file.password (
Optional[str]) – Password for encrypted private key file, defaults to None.hash_alg (
Optional[EnumHashAlgorithm]) – Hash algorithm for the signature, defaults to None.search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None.kwargs (
Union[str,int,bool,EnumHashAlgorithm]) – Additional keyword arguments for signing operation.
- Raises:
SPSDKError – Invalid private key or file not found.
- property hash_alg: EnumHashAlgorithm | None#
Get hash algorithm used by the signature provider.
- Returns:
Hash algorithm enumeration value, None if not set.
-
identifier:
str= 'file'#
- info()#
Return basic information about the signature provider.
The method extends the parent class info with additional details about the key file path used by this signature provider.
- Return type:
str- Returns:
Formatted string containing signature provider information including key path.
- sign(data)#
Sign data using the private key.
- Parameters:
data (
bytes) – Data to be signed.- Return type:
bytes- Returns:
Digital signature of the input data.
- property signature_length: int#
Get signature length in bytes.
- Returns:
Length of the signature in bytes.
- class spsdk.crypto.signature_provider.SignatureProvider#
Bases:
ServiceProviderAbstract base class for cryptographic signature providers in SPSDK.
This class defines the interface for all signature providers that handle cryptographic signing operations across NXP MCU portfolio. Signature providers abstract the underlying signing mechanisms (hardware tokens, files, remote services) and provide unified API for generating digital signatures.
- Variables:
identifier – Unique identifier for the signature provider type.
reserved_keys – Configuration keys reserved by the base class.
legacy_identifier_name – Legacy name for backward compatibility.
plugin_identifier – Plugin system identifier for dynamic loading.
- get_signature(data, encoding=None)#
Get signature with optional encoding format.
In case of ECC signature, the NXP format (r+s) is used by default. The method automatically detects ECC signatures and applies the specified encoding format. Non-ECC signatures are returned as-is.
- Parameters:
data (
bytes) – Data to be signed.encoding (
Optional[SPSDKEncoding]) – Encoding type of output signature, defaults to NXP format for ECC.
- Return type:
bytes- Returns:
Signature of the data in the specified encoding format.
-
identifier:
str= 'INVALID'#
-
legacy_identifier_name:
str= 'sp_type'#
-
plugin_identifier:
str= 'spsdk.sp'#
- reserved_keys = ['type', 'identifier', 'search_paths']#
- abstract sign(data)#
Sign data using the configured signature provider.
- Parameters:
data (
bytes) – Data to be signed.- Return type:
bytes- Returns:
Digital signature of the input data.
- abstract property signature_length: int#
Get the length of the signature in bytes.
- Returns:
Length of the signature in bytes.
- try_to_verify_public_key(public_key)#
Verify public key by signature provider if verify method is implemented.
The method attempts to verify that the provided public key corresponds to the private key held by the signature provider. If the public key is provided as bytes, it will be parsed automatically. The verification is optional and depends on provider implementation.
- Parameters:
public_key (
Union[PublicKey,bytes]) – Public key to be verified. If used as bytes, it can be in PEM/DER/NXP format- Raises:
SPSDKUnsupportedOperation – The verify_public_key method is not implemented
SPSDKKeysNotMatchingError – The verification of key-pair integrity failed
- Return type:
None
- verify_public_key(public_key)#
Verify if given public key matches private key.
- Parameters:
public_key (
PublicKey) – Public key to verify against the private key.- Raises:
SPSDKUnsupportedOperation – Verify method is not supported.
- Return type:
bool
Crypto module OSCCA#
SPSDK OSCCA cryptographic algorithms support utilities.
This module provides support detection and utilities for OSCCA (Office of State Commercial Cryptography Administration) algorithms including SM2 elliptic curve cryptography and SM3 hash functions used in Chinese cryptographic standards.
- class spsdk.crypto.oscca.SM2Encoder(*args: Any, **kwargs: Any)#
Bases:
objectASN.1 encoder and decoder for SM2 cryptographic keys and signatures.
This singleton class provides comprehensive ASN.1 encoding and decoding functionality for SM2 (ShangMi 2) cryptographic operations, supporting both private and public key formats as well as signature data conversion between raw and BER formats.
- decode_private_key(data)#
Decode private SM2 key from binary data.
The method parses the binary data to extract private and public key components and validates the public key length.
- Parameters:
data (
bytes) – Binary data containing the encoded SM2 private key.- Raises:
SPSDKError – Invalid length of public key data.
- Return type:
- Returns:
SM2PrivateKey object containing the decoded private and public keys.
- decode_public_key(data)#
Parse public SM2 key set from binary data.
Decodes binary data containing a public SM2 key and creates an SM2PublicKey object. The method validates that the decoded key data has the expected length of 128 bytes.
- Parameters:
data (
bytes) – Binary data containing the encoded SM2 public key.- Raises:
SPSDKError – Invalid length of public key data (expected 128 bytes).
- Return type:
- Returns:
SM2PublicKey object containing the decoded public key.
- decode_signature(data)#
Decode BER signature into r||s coordinates.
- Parameters:
data (
bytes) – BER encoded signature data to be decoded.- Return type:
bytes- Returns:
Decoded signature as concatenated r||s coordinates in bytes format.
- encode_private_key(keys)#
Encode private SM2 key set from keyset.
The method encodes both private and public keys from the SM2 key pair into a binary format using OSCCA ASN.1 encoding standards.
- Parameters:
keys (
SM2PrivateKey) – SM2 private key object containing both private and public key components.- Return type:
bytes- Returns:
Encoded private key data in binary format.
- encode_public_key(key)#
Encode public SM2 key from SM2PublicKey.
- Parameters:
key (
SM2PublicKey) – SM2 public key object to be encoded.- Return type:
bytes- Returns:
Encoded public key as bytes.
- encode_signature(data)#
Encode raw r||s signature into BER format.
- Parameters:
data (
bytes) – Raw signature data containing concatenated r and s values.- Return type:
bytes- Returns:
BER-encoded signature bytes.
- class spsdk.crypto.oscca.SM2PrivateKey(private: str, public: str)#
Bases:
NamedTupleSM2 private key representation for OSCCA cryptographic operations.
This class provides a simple container for SM2 private and public key pairs used in Chinese cryptographic standards. It stores both the private key value and its corresponding public key as string representations.
Create new instance of SM2PrivateKey(private, public)
-
private:
str# Alias for field number 0
-
public:
str# Alias for field number 1
-
private:
- class spsdk.crypto.oscca.SM2PublicKey(public: str)#
Bases:
NamedTupleSM2 Public Key representation for OSCCA cryptographic operations.
This class provides a simple structure for holding SM2 public key data as a string representation, used in Chinese cryptographic standards.
Create new instance of SM2PublicKey(public,)
-
public:
str# Alias for field number 0
-
public:
- spsdk.crypto.oscca.sanitize_pem(data)#
Convert PEM data into DER format.
Extracts the base64-encoded data between PEM markers containing ‘KEY’ and converts it to DER (Distinguished Encoding Rules) format. The method handles various PEM key formats by looking for lines containing ‘KEY’ as start/end markers.
- Parameters:
data (
bytes) – Input data that may be in PEM or DER format.- Raises:
SPSDKError – When PEM data is corrupted or cannot be decoded.
- Return type:
bytes- Returns:
DER-formatted data as bytes.
Crypto module types#
SPSDK cryptographic type definitions and enumerations.
This module provides common cryptographic types, enumerations, and constants used across SPSDK for cryptographic operations and certificate handling.
- class spsdk.crypto.crypto_types.SPSDKEncoding(value)#
Bases:
EnumSPSDK cryptographic encoding enumeration.
This enumeration extends the standard cryptography library encodings with NXP-specific encoding formats. It provides utilities for encoding detection, conversion between SPSDK and cryptography library formats, and validation of supported encoding types for cryptographic operations.
- DER = 'DER'#
- NXP = 'NXP'#
- PEM = 'PEM'#
- static all()#
Get all supported encodings.
- Return type:
dict[str, SPSDKEncoding]- Returns:
Dictionary mapping encoding names to SPSDKEncoding enum values.
- static cryptography_encodings()#
Get all supported encodings by cryptography.
Returns a dictionary mapping encoding names to their corresponding SPSDKEncoding values that are supported by the cryptography library.
- Return type:
dict[str, SPSDKEncoding]- Returns:
Dictionary with encoding names as keys and SPSDKEncoding enum values as values.
- static get_cryptography_encodings(encoding)#
Get cryptography library encoding from SPSDK encoding.
Converts SPSDK encoding enumeration to the corresponding cryptography library encoding format for use with cryptography operations.
- Parameters:
encoding (
SPSDKEncoding) – SPSDK encoding type to convert.- Raises:
SPSDKError – If the encoding format is not supported by cryptography.
- Return type:
Encoding- Returns:
Corresponding cryptography library encoding.
- static get_file_encodings(data)#
Determine encoding type of cryptographic data.
Analyzes the provided data to detect whether it uses PEM (text-based) or DER (binary) encoding format by checking for UTF-8 decodability and PEM markers.
- Parameters:
data (
bytes) – Raw bytes of the data file to analyze for encoding detection.- Return type:
- Returns:
Detected encoding type (SPSDKEncoding.PEM or SPSDKEncoding.DER).
Crypto module RNG#
SPSDK cryptographic random number generation utilities.
This module provides secure random number and byte generation functions for cryptographic operations within SPSDK. It offers convenient wrappers around Python’s secrets module for generating random bytes, hexadecimal strings, and bounded random integers.
- spsdk.crypto.rng.rand_below(upper_bound)#
Generate a random integer in the specified range.
Returns a cryptographically secure random number in the range [0, upper_bound] using the underlying randbelow function.
- Parameters:
upper_bound (
int) – The upper bound for the random number generation (inclusive).- Return type:
int- Returns:
Random integer between 0 and upper_bound (inclusive).
- spsdk.crypto.rng.random_bytes(length)#
Generate cryptographically secure random bytes.
This function provides a secure source of randomness suitable for cryptographic operations and security-sensitive applications.
- Parameters:
length (
int) – The number of random bytes to generate.- Raises:
ValueError – If length is negative.
- Return type:
bytes- Returns:
Cryptographically secure random bytes of specified length.
- spsdk.crypto.rng.random_hex(length)#
Generate random hexadecimal string of specified byte length.
The method creates a cryptographically secure random hexadecimal string using the underlying token_hex function.
- Parameters:
length (
int) – The length in bytes of the random data to generate.- Return type:
str- Returns:
Random hexadecimal string representation (twice the byte length).
Crypto exceptions#
SPSDK cryptographic exceptions module.
This module defines custom exception classes for handling cryptographic errors within the SPSDK framework, providing specific error types for crypto operations and key validation failures.
- exception spsdk.crypto.exceptions.SPSDKKeysNotMatchingError(desc=None)#
Bases:
SPSDKPCryptoErrorSPSDK cryptographic key mismatch exception.
This exception is raised when cryptographic key pairs do not match during validation or verification operations in SPSDK cryptographic functions.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.crypto.exceptions.SPSDKPCryptoError(desc=None)#
Bases:
SPSDKErrorGeneral SPSDK Crypto Error.
Base exception class for all cryptographic operations within SPSDK. This exception is raised when cryptographic operations fail, including key generation, encryption, decryption, signing, and verification errors.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.