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