Image Module API#
SPSDK image processing and generation utilities.
This module provides comprehensive functionality for creating, manipulating, and processing various types of secure boot images, including bootable images, Device Configuration Data (DCD), and Security Reference Key (SRK) management.
Image Segments#
SPSDK base classes for image segments.
This module provides abstract base functionality for image segments used across SPSDK image processing. It defines the core SegmentBase class that serves as foundation for all segment implementations in the image module.
- class spsdk.image.segments_base.SegmentBase(family)#
Bases:
FeatureBaseClassBase class for image segment implementations.
This abstract class provides common functionality for all image segment types in SPSDK, including register management, binary export capabilities, and memory type configuration handling across different chip families.
- Variables:
FEATURE – Feature identifier used for database lookups.
Initialize segment base with chip family configuration.
- Parameters:
family (
FamilyRevision) – Chip family and revision information used to configure the segment.- Raises:
SPSDKValueError – Unsupported family.
-
FEATURE:
str= 'unknown'#
- export()#
Export segment to binary representation.
- Return type:
bytes- Returns:
Binary data of the segment.
- classmethod get_memory_types_config(family)#
Get memory types data from database.
- Parameters:
family (
FamilyRevision) – Chip family.- Return type:
dict[str,dict]- Returns:
Dictionary containing memory types configuration data.
- classmethod get_supported_memory_types(family=None)#
Get list of supported memory types data from database.
The method retrieves memory types either for a specific chip family or all available memory types from the database feature configuration.
- Parameters:
family (
Optional[FamilyRevision]) – Chip family to get memory types for. If None, returns all available types.- Return type:
list[MemoryType]- Returns:
List of supported memory types.
TrustZone#
SPSDK TrustZone configuration management utilities.
This module provides functionality for handling TrustZone security configuration data in SPSDK image processing. It supports both legacy and version 2 TrustZone record formats for configuring memory regions and security policies.
- class spsdk.image.trustzone.TrustZone(family)#
Bases:
FeatureBaseClassTrustZone configuration manager for ARM Cortex-M33 processors.
This class provides functionality to create and manage binary data for configuring the TrustZone security engine in ARM Cortex-M33 based NXP MCUs. It handles TrustZone preset configurations, validation schemas, and binary export operations.
- Variables:
FEATURE – Database manager feature identifier for TrustZone operations.
PRE_VALIDATION_CFG_HOOK – Pre-validation hook for trustZonePreset register keys.
Initialize the TrustZone configuration for specified family.
Creates a new TrustZone instance with registers configuration for the given MCU family. Validates that the family supports TrustZone functionality.
- Parameters:
family (
FamilyRevision) – MCU family and revision specification for TrustZone configuration.- Raises:
SPSDKValueError – If the specified family doesn’t support TrustZone.
-
FEATURE:
str= 'tz'#
- PRE_VALIDATION_CFG_HOOK = <spsdk.utils.registers.RegistersPreValidationHook object>#
- export()#
Export TrustZone configuration data as binary representation.
The method serializes the current TrustZone register configuration into a binary format that can be used for device programming or storage.
- Return type:
bytes- Returns:
Binary representation of TrustZone configuration data.
- get_config(data_path='./')#
Create configuration of the TrustZone.
The method generates a configuration dictionary containing family information, revision, output file path, and TrustZone preset settings.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary with TrustZone settings.
- classmethod get_validation_schemas(family)#
Get validation schemas for TrustZone configuration.
Creates validation schemas for both family configuration and TrustZone preset settings, updating the family schema with supported families and integrating the TrustZone register validation schema.
- Parameters:
family (
FamilyRevision) – Family description containing chip family and revision information.- Raises:
SPSDKError – Family or revision is not supported.
- Return type:
list[dict[str,Any]]- Returns:
List containing family validation schema and TrustZone configuration schema.
- classmethod get_validation_schemas_from_cfg(config)#
Get validation schemas based on configuration.
Retrieves the appropriate validation schemas for TrustZone configuration by first validating the provided configuration against basic schemas, then loading the family revision and returning the family-specific validation schemas. This method can be overridden in subclasses for custom behavior.
- Parameters:
config (
Config) – Valid configuration object containing TrustZone settings- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the specified family
- Raises:
SPSDKError – Invalid configuration or unsupported family
- property is_customized: bool#
Check if the TrustZone configuration has customized values.
This method determines whether the TrustZone registers contain custom values or are still at their reset/default state.
- Returns:
True if the TrustZone is customized, False otherwise.
- classmethod load_from_config(config)#
Create TrustZone instance from configuration data.
This alternate constructor initializes a TrustZone object using the provided configuration, loading family information and trust zone preset settings.
- Parameters:
config (
Config) – Configuration object containing family and trustZonePreset data.- Raises:
SPSDKError – Invalid configuration file.
- Return type:
Self- Returns:
TrustZone class instance.
- classmethod parse(data, family=None)#
Parse TrustZone configuration from bytes array.
- Parameters:
data (
bytes) – Bytes array containing TrustZone configuration data.family (
Optional[FamilyRevision]) – Family revision required for proper parsing of the configuration.
- Raises:
SPSDKValueError – If family parameter is not provided.
- Return type:
Self- Returns:
Parsed TrustZone instance with loaded configuration.
- class spsdk.image.trustzone.TrustZoneType(tag, label, description=None)#
Bases:
SpsdkEnumTrustZone configuration type enumeration.
Defines the available TrustZone configuration modes for secure and non-secure world partitioning in ARM Cortex-M processors.
- CUSTOM = (1, 'CUSTOM', 'TrustZone enabled with custom settings')#
- DISABLED = (2, 'DISABLED', 'Disabled')#
- ENABLED = (0, 'ENABLED', 'TrustZone enabled with default settings')#
Support for BEE encryption for RT10xx devices#
SPSDK Bus Encryption Engine (BEE) support module.
This module provides comprehensive functionality for handling BEE encryption used in NXP MCUs. It includes classes for managing BEE regions, protection blocks, key information blocks (KIB), and AES encryption modes for secure boot and runtime protection of code and data.
- class spsdk.image.bee.Bee(family, headers, input_images)#
Bases:
FeatureBaseClassSPSDK Bus Encryption Engine (BEE) manager.
This class handles encryption and decryption operations for NXP MCU images using the Bus Encryption Engine feature. It manages BEE region headers and processes input images to generate encrypted binary outputs with proper region configuration.
- Variables:
FEATURE – Database feature identifier for BEE operations.
Initialize BEE (Bus Encryption Engine) configuration.
Creates a new BEE instance with the specified family, region headers, and input images for encryption processing.
- Parameters:
family (
FamilyRevision) – The target MCU/MPU family and revision information.headers (
list[Optional[BeeRegionHeader]]) – List of BEE region headers, may contain None values for unused regions.input_images (
list[tuple[bytes,int]]) – List of tuples containing image data and corresponding base addresses.
-
FEATURE:
str= 'bee'#
- static check_image_overlaps(images)#
Check for overlaps in input images.
This method validates that no two images in the provided list have overlapping memory regions by comparing their base addresses and sizes.
- Parameters:
images (
list[tuple[bytes,int]]) – List of tuples containing (image_data, base_address) where image_data is bytes and base_address is int- Raises:
SPSDKOverlapError – If any two images overlap in memory space
- Return type:
None
- static check_overlaps(bee_headers, start_addr)#
Check for overlaps in regions.
Validates that a given start address does not overlap with any existing BEE (Bus Encryption Engine) regions defined in the provided headers.
- Parameters:
bee_headers (
list[Optional[BeeRegionHeader]]) – List of BeeRegionHeader objects to check against.start_addr (
int) – Start address of a region to be checked for overlaps.
- Raises:
SPSDKOverlapError – If the address is inside any existing region.
- Return type:
None
- export()#
Export encrypted binary image.
Handles both single and multiple input images. For single images, returns the encrypted image directly. For multiple images, combines them into a single binary with proper address alignment, fills gaps with 0xFF (flash erase value), and encrypts the result.
- Return type:
bytes- Returns:
Encrypted binary image data, or empty bytes if no input images are available.
- export_headers()#
Export BEE headers for all configured regions.
The method iterates through all BEE headers and exports them as bytes. If a header is not configured (None), it remains None in the output list.
- Return type:
list[Optional[bytes]]- Returns:
List of exported BEE region headers as bytes, or None for unconfigured regions.
- get_config(data_path='./')#
Create configuration of the Feature.
- Parameters:
data_path (
str) – Path to directory containing configuration data files.- Raises:
SPSDKNotImplementedError – Method is not implemented in base class.
- Return type:
Config
- classmethod get_validation_schemas(family)#
Get list of validation schemas for BEE configuration.
The method retrieves and combines validation schemas including family-specific schemas, BEE output schemas, and general BEE schemas. It updates the family schema with supported families for the given family revision.
- Parameters:
family (
FamilyRevision) – The MCU/MPU family revision to get validation schemas for.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for BEE configuration.
- classmethod load_from_config(config)#
Load BEE configuration and create BEE image object.
Converts the provided configuration into a BEE (Bus Encryption Engine) image object, handling both single and multi-image modes with engine selection and protected regions.
- Parameters:
config (
Config) – Configuration dictionary containing BEE settings, engines, and data blobs.- Return type:
Self- Returns:
Initialized Bee object with configured headers and input images.
- Raises:
SPSDKError – Invalid BEE engine count or configuration errors.
- classmethod parse(data)#
Parse object from bytes array.
- Parameters:
data (
bytes) – Input binary data to parse- Raises:
SPSDKNotImplementedError – Method not implemented in base class
- Return type:
Self
- class spsdk.image.bee.BeeBaseClass#
Bases:
objectBEE base class for binary data serialization and validation.
This abstract base class provides common functionality for BEE (Bus Encryption Engine) related classes that need to serialize to/from binary format. It defines the interface for size calculation, data validation, export operations, and comparison methods.
- Variables:
_FORMAT – Binary format string for struct.pack/unpack operations (must be defined in subclasses).
- classmethod check_data_to_parse(data)#
Check if binary data has sufficient size for parsing.
Validates that the provided binary data contains enough bytes to be successfully parsed by the class.
- Parameters:
data (
bytes) – Binary data to be validated for parsing.- Raises:
SPSDKError – If size of the data is not sufficient.
- Return type:
None
- export()#
Export binary representation of the region.
The method updates and validates the region before serialization to ensure data consistency and integrity.
- Return type:
bytes- Returns:
Binary representation of the region (serialization).
- classmethod get_size()#
Get size of the exported binary data.
- Return type:
int- Returns:
Size of the exported binary data in bytes.
- property size: int#
Get size of the exported binary data.
- Returns:
Size of the exported binary data in bytes.
- update()#
Updates internal fields of the instance.
This method refreshes and synchronizes the internal state of the BEE (Bus Encryption Engine) instance to ensure all fields are current and consistent.
- Return type:
None
- validate()#
Validate the configuration of the BEE instance.
Ensures all required configuration parameters are properly set and valid. It is recommended to call this method before export and after parsing.
- Raises:
SPSDKError – Invalid configuration detected.
- Return type:
None
- class spsdk.image.bee.BeeFacRegion(start=0, length=0, protected_level=0)#
Bases:
BeeBaseClassBEE Factory Access Control (FAC) region.
This class represents a memory region configuration for BEE (Bus Encryption Engine) Factory Access Control, defining protected memory areas with specific access levels and encryption boundaries aligned to 1KB boundaries.
- Variables:
_FORMAT – Binary format string for struct pack/unpack operations.
Initialize BEE FAC region configuration.
Creates a new FAC (Flexible Access Control) region with specified memory boundaries and protection settings for BEE encryption engine.
- Parameters:
start (
int) – Start address of FAC region, must be aligned at 1KB boundary.length (
int) – Length of FAC region in bytes, must be aligned at 1KB boundary.protected_level (
int) – Protection level (0=unprotected, 1-3=increasing protection).
- property end_addr: int#
Get end address of the region.
The end address represents the first address after the region (last address + 1).
- Returns:
End address of the region.
- export()#
Export the binary representation of the BEE region configuration.
The method exports the current BEE region configuration including the parent class data followed by the region-specific parameters (start address, end address, protection level, and padding).
- Return type:
bytes- Returns:
Binary representation of the BEE region configuration.
- classmethod parse(data)#
Parse binary data to create BeeFacRegion instance.
Deserializes binary data into a BeeFacRegion object by extracting start address, end address, and protection level from the structured data format.
- Parameters:
data (
bytes) – Binary data to be parsed into BeeFacRegion instance.- Return type:
Self- Returns:
BeeFacRegion instance created from the parsed binary data.
- Raises:
SPSDKError – If reserved area contains non-zero values.
- validate()#
Validate the BEE encryption region configuration.
Performs comprehensive validation of the encryption region including address alignment, protection level bounds, and address range validity.
- Raises:
SPSDKError – Invalid encryption block address alignment.
SPSDKError – Invalid protected level (must be 0-3).
SPSDKError – Invalid start/end address range or bounds.
- Return type:
None
- class spsdk.image.bee.BeeKIB(kib_key=None, kib_iv=None)#
Bases:
BeeBaseClassBEE Key Information Block (KIB) for encryption operations.
This class manages the AES key and initialization vector used to encrypt PRDB (Protected Region Data Block) content in BEE (Bus Encryption Engine) operations. It provides functionality for key generation, validation, serialization, and deserialization.
- Variables:
_KEY_LEN – AES key length in bytes (16 bytes for AES-128).
_FORMAT – Binary format string for struct pack/unpack operations.
Initialize BEE (Bus Encryption Engine) configuration.
Creates a new BEE instance with AES encryption parameters. If key or IV are not provided, random values will be generated automatically.
- Parameters:
kib_key (
Optional[bytes]) – AES encryption key for Key Info Block, defaults to random 16 byteskib_iv (
Optional[bytes]) – AES initialization vector for Key Info Block, defaults to random 16 bytes
- export()#
Export binary representation of the BEE region.
Serializes the BEE region data including the parent region data and appends the KIB key and initialization vector using the struct format.
- Return type:
bytes- Returns:
Binary representation of the complete BEE region data.
- classmethod parse(data)#
Parse binary data to create BeeKIB instance.
Deserializes binary data containing key and initialization vector information to reconstruct a BeeKIB object with proper validation.
- Parameters:
data (
bytes) – Binary data to be parsed containing key and IV information.- Raises:
SPSDKError – Invalid input data size or format.
- Return type:
Self- Returns:
BeeKIB instance created from the parsed binary data.
- validate()#
Validates the BEE instance settings.
Checks that both the KIB key and KIB IV have the correct length according to the specification requirements.
- Raises:
SPSDKError – If invalid length of kib key.
SPSDKError – If invalid length of kib iv.
- Return type:
None
- class spsdk.image.bee.BeeProtectRegionBlock(encr_mode=BeeProtectRegionBlockAesMode(tag=1, label='CTR', description=None), lock_options=0, counter=None)#
Bases:
BeeBaseClassBEE protect region block (PRDB).
This class represents a Bus Encryption Engine (BEE) protection region data block that manages encrypted memory regions and their associated Flash Access Control (FAC) regions. It handles AES encryption configuration, lock options, and counter values for secure boot operations.
- Variables:
TAGL – Low TAG identifier for the header (0x5F474154).
TAGH – High TAG identifier for the header (0x52444845).
VERSION – Format version identifier (0x56010000).
FAC_REGIONS – Maximum number of FAC regions supported (4).
SIZE – Total size of the protection region block (0x100 bytes).
Initialize BEE protect region block.
Creates a new BEE (Bus Encryption Engine) protect region block with specified encryption mode, lock options, and counter value.
- Parameters:
encr_mode (
BeeProtectRegionBlockAesMode) – AES encryption mode for the protect region.lock_options (
int) – Lock options as 32-bit number.counter (
Optional[bytes]) – Counter for AES-CTR mode (16 bytes). If None, random value is used.
- FAC_REGIONS = 4#
- SIZE = 256#
- TAGH = 1380206661#
- TAGL = 1598505300#
- VERSION = 1442906112#
- add_fac(fac)#
Add FAC region to the BEE configuration.
Appends a Factory Access Control region to the list of FAC regions and updates the internal state of the BEE configuration.
- Parameters:
fac (
BeeFacRegion) – Factory Access Control region to be added to the configuration- Return type:
None
- encrypt_block(key, start_addr, data)#
Encrypt block located in any FAC region.
The method encrypts data using AES/CTR mode if the block is within any configured FAC (Flash Access Control) region. Data outside FAC regions remains unchanged.
- Parameters:
key (
bytes) – AES encryption key (must be 16 bytes)start_addr (
int) – Start address of the data blockdata (
bytes) – Binary block to be encrypted; size must not exceed BEE_ENCR_BLOCK_SIZE
- Return type:
bytes- Returns:
Encrypted block if inside any FAC region; untouched block otherwise
- Raises:
SPSDKError – When incorrect length of binary block
SPSDKError – When encryption mode different from AES/CTR provided
SPSDKError – When invalid length of key
SPSDKError – When invalid range of region
- export()#
Export the BEE region to binary format.
Serializes the BEE region including header information, FAC regions, and padding to create a binary representation suitable for deployment.
- Return type:
bytes- Returns:
Binary representation of the complete BEE region with proper formatting.
- property fac_count: int#
Get the number of Factory Access Control regions.
- Returns:
Number of Factory Access Control regions.
- classmethod get_size()#
Get size of the exported binary data.
- Return type:
int- Returns:
Size of the exported binary data in bytes.
- is_inside_region(start_addr)#
Check if the start address lies within the FAC region.
- Parameters:
start_addr (
int) – Start address of the data to check.- Return type:
bool- Returns:
True if the address is within the region, False otherwise.
- classmethod parse(data)#
Parse BEE protect region block from binary data.
Deserializes binary data into a BeeProtectRegionBlock instance by extracting header information, validating format and version, and parsing associated FAC regions.
- Parameters:
data (
bytes) – Binary data containing the BEE protect region block structure.- Return type:
Self- Returns:
BeeProtectRegionBlock instance created from the parsed binary data.
- Raises:
SPSDKError – If tag is invalid, version is unsupported, reserved area is non-zero, or format does not match expected structure.
- update()#
Update encryption region boundaries based on FAC regions.
The method updates all FAC (Flash Access Control) regions first, then calculates and sets the minimum start address and maximum end address across all FAC regions to define the overall encryption region boundaries.
- Raises:
SPSDKError – If FAC region update fails.
- Return type:
None
- validate()#
Validate the BEE protect region block settings.
Performs comprehensive validation of all configuration parameters including address ranges, encryption mode, counter format, and FAC regions.
- Raises:
SPSDKError – Invalid start address (negative or exceeds 32-bit range).
SPSDKError – Invalid end address or start address greater than end address.
SPSDKError – Unsupported encryption mode (only AES/CTR is supported).
SPSDKError – Invalid counter length (must be 16 bytes).
SPSDKError – Invalid counter format (last 4 bytes must be zero).
SPSDKError – Invalid FAC regions count (must be 1-8).
SPSDKError – Invalid FAC region configuration from nested validation.
- Return type:
None
- class spsdk.image.bee.BeeProtectRegionBlockAesMode(tag, label, description=None)#
Bases:
SpsdkEnumAES mode selection enumeration for BEE PRDB encryption.
This enumeration defines the available AES encryption modes that can be used for Bus Encryption Engine (BEE) Protect Region Data Block operations.
- CTR = (1, 'CTR')#
- ECB = (0, 'ECB')#
- class spsdk.image.bee.BeeRegionHeader(prdb=None, sw_key=None, kib=None)#
Bases:
BeeBaseClassBEE keys and regions header.
This class manages the Bus Encryption Engine (BEE) region header structure, which contains protected region blocks, software keys, and key information blocks for secure boot operations.
- Variables:
PRDB_OFFSET – Offset of the Protected Region Block in the header (0x80).
SIZE – Total size of the header including padding (0x200 bytes).
Initialize BEE (Bus Encryption Engine) configuration.
Creates a new BEE instance with protection region block, software key for KIB encryption, and key information block. Default values are generated if parameters are not provided.
- Parameters:
prdb (
Optional[BeeProtectRegionBlock]) – Protection region block configuration, defaults to new BeeProtectRegionBlock.sw_key (
Optional[bytes]) – 16-byte software key used to encrypt KIB content, defaults to random key.kib (
Optional[BeeKIB]) – Key information block containing encryption keys, defaults to new BeeKIB.
- PRDB_OFFSET = 128#
- SIZE = 512#
- add_fac(fac)#
Add FAC region to the BEE configuration.
Appends a new FAC (Flash Access Control) region to the internal PRDB (Protected Region Database) for BEE encryption configuration.
- Parameters:
fac (
BeeFacRegion) – FAC region configuration to be added to the BEE setup.- Return type:
None
- encrypt_block(start_addr, data)#
Encrypt block located in any FAC region.
The method encrypts a binary block if it falls within any configured FAC (Flash Access Control) region using the internal software key and PRDB configuration.
- Parameters:
start_addr (
int) – Start address of the data block.data (
bytes) – Binary block to be encrypted; the block size must be BEE_ENCR_BLOCK_SIZE.
- Return type:
bytes- Returns:
Encrypted block if it is inside any FAC region; untouched block if it is not in any FAC region.
- export()#
Export BEE region to binary representation.
Serializes the BEE region including KIB (Key Info Block) and PRDB (Protected Region Data Block) with proper encryption and padding to create the final binary output.
- Return type:
bytes- Returns:
Binary representation of the complete BEE region with encrypted data blocks.
- property fac_regions: Sequence[BeeFacRegion]#
Get list of Factory Access Control regions.
- Returns:
Sequence of Factory Access Control regions.
- classmethod get_size()#
Get size of the exported binary data.
- Return type:
int- Returns:
Size of the exported binary data in bytes.
- is_inside_region(start_addr)#
Check if start address lies within any FAC region.
- Parameters:
start_addr (
int) – Start address of the data to check.- Return type:
bool- Returns:
True if the address is within any FAC region, False otherwise.
- classmethod parse(data, sw_key=b'')#
Parse binary data to create BEE instance.
Deserializes encrypted binary data using the provided software key to decrypt the EKIB (Encrypted Key Info Block) and PRDB (Protect Region Data Block) data.
- Parameters:
data (
bytes) – Binary data to be parsed containing encrypted BEE information.sw_key (
bytes) – 16-byte software key used to decrypt the EKIB data.
- Return type:
Self- Returns:
BEE instance created from the parsed binary data.
- Raises:
SPSDKError – If invalid software key length (must be 16 bytes).
- sw_key_fuses()#
Get SW key fuse values for processor burning.
The method extracts the software key and converts it into a sequence of fuse values that should be burned into the processor. The result is ordered so that the first value should be burned to the lowest address.
- Return type:
Sequence[int]- Returns:
Sequence of fuse values for SW key to be burned into processor.
- update()#
Updates internal fields of the instance.
This method calls the parent class update method and then updates the internal Key Information Block (KIB) and Protected Region Database (PRDB) components.
- Return type:
None
- validate()#
Validates settings of the BEE instance.
The method validates the Key Info Block (KIB) and Protection Region Database (PRDB) components, and ensures the software key has the correct length of 16 bytes.
- Raises:
SPSDKError – If KIB settings are invalid, PRDB settings are invalid, or software key length is not 16 bytes.
- Return type:
None
Support for KeyStore used in MasterBootImage#
Module provides support for KeyStore used in MasterBootImage.
- class spsdk.image.keystore.KeySourceType(tag, label, description=None)#
Bases:
SpsdkEnumDevice key source enumeration for SPSDK operations.
This enumeration defines the available sources where device keys can be stored, including OTP (One-Time Programmable) memory and KeyStore locations.
- KEYSTORE = (1, 'KEYSTORE', 'Device keys stored in KeyStore')#
- OTP = (0, 'OTP', 'Device keys stored in OTP')#
- class spsdk.image.keystore.KeyStore(key_source, key_store=None)#
Bases:
objectSPSDK KeyStore manager for Master Boot Image operations.
This class manages cryptographic key storage and derivation for secure boot operations, supporting different key sources and providing key derivation functionality for encryption, authentication, and OTFAD operations.
- Variables:
KEY_STORE_SIZE – Size of key store in bytes (device-specific).
SBKEK_SIZE – Size of Secure Binary KEK in bytes.
OTP_MASTER_KEY_SIZE – Size of OTP master key in bytes.
OTFAD_KEY_SIZE – Size of OTFAD key in bytes.
Initialize Keystore.
- Parameters:
key_source (
KeySourceType) – Device key source type.key_store (
Optional[bytes]) – Initial content of the key store in the bootable image; None if empty.
- Raises:
SPSDKError – If invalid key-store size.
SPSDKError – KeyStore can be initialized only if key_source == KEYSTORE.
- KEY_STORE_SIZE = 1424#
- OTFAD_KEY_SIZE = 16#
- OTP_MASTER_KEY_SIZE = 32#
- SBKEK_SIZE = 32#
- static derive_enc_image_key(master_key)#
Derive encryption image key from master key.
The method derives the encryption key used to decrypt encrypted images during boot process from the master key stored in OTP memory using AES ECB encryption.
- Parameters:
master_key (
bytes) – Master key stored in OTP memory (must be 32 bytes).- Return type:
bytes- Returns:
Derived key used to decrypt encrypted images during boot.
- Raises:
SPSDKError – If invalid length of master key.
- static derive_hmac_key(hmac_key)#
Derive HMAC key from master or user key.
This method performs AES-ECB encryption on a zero-filled 16-byte block using the provided HMAC key to derive the final HMAC key for image header authentication.
- Parameters:
hmac_key (
bytes) – Master key (for key_source == OTP) or user key (for key_source == KEYSTORE), must be exactly 32 bytes long.- Return type:
bytes- Returns:
Derived key used for image header authentication in LoadToRam images.
- Raises:
SPSDKError – If invalid length of hmac key (must be 32 bytes).
- static derive_otfad_kek_key(master_key, otfad_input)#
Derive OTFAD KEK key from master key and OTFAD input.
This method uses AES ECB encryption to derive the OTFAD Key Encryption Key from the provided master key and OTFAD input data.
- Parameters:
master_key (
bytes) – 32-byte master key stored in OTP memoryotfad_input (
bytes) – 16-byte OTFAD input data stored in OTP memory
- Return type:
bytes- Returns:
Derived OTFAD encryption key for FLASH encryption/decryption
- Raises:
SPSDKError – Invalid length of master key (must be 32 bytes)
SPSDKError – Invalid length of OTFAD input (must be 16 bytes)
- static derive_sb_kek_key(master_key)#
Derive SBKEK key from master key.
This method derives a Secure Binary Key Encryption Key (SBKEK) from a master key using AES-ECB encryption with a specific derivation pattern.
- Parameters:
master_key (
bytes) – 32-byte master key stored in OTP memory.- Return type:
bytes- Returns:
Derived encryption key for handling SB2 file (update capsule).
- Raises:
SPSDKError – If master key length is not exactly 32 bytes.
- export()#
Export binary key store content.
Returns the binary representation of the key store data, or empty bytes if the key store is empty.
- Return type:
bytes- Returns:
Binary key store content as bytes, empty bytes for empty key-store.
- property key_source: KeySourceType#
Get the device key source type.
- Returns:
The key source type for the device.
Master Boot Image#
SPSDK Master Boot Image generation and management utilities.
This module provides functionality for creating, configuring, and managing Master Boot Images (MBI) used in NXP MCU secure boot process. It includes the main MasterBootImage class for image creation and configuration template generation utilities.
- class spsdk.image.mbi.mbi.MasterBootImage(family, **kwargs)#
Bases:
FeatureBaseClassMaster Boot Image Interface.
This class provides a unified interface for creating and managing Master Boot Images across NXP MCU portfolio. It handles image creation, authentication, encryption, and signing operations for different target types and authentication methods.
- Variables:
FEATURE – Database feature identifier for MBI operations.
IMAGE_TYPE – Default image type for plain images.
IMAGE_TARGET – Default target location for image loading.
IMAGE_AUTHENTICATIONS – Default authentication method.
IMAGE_TYPES – Supported image target types and aliases.
Initialize MBI (Master Boot Image) instance.
Sets up the MBI object with the specified family revision and additional parameters. Validates that all required class members are present after initialization through mixins.
- Parameters:
family (
FamilyRevision) – The target MCU family and revision information.kwargs (
Any) – Additional initialization parameters specific to the dynamic class implementation.
- Raises:
SPSDKValueError – When a required class member is missing after mixin initialization.
-
FEATURE:
str= 'mbi'#
- IMAGE_AUTHENTICATIONS = 'plain'#
- IMAGE_TARGET = 'load_to_ram'#
- IMAGE_TYPE = (0, 'PLAIN_IMAGE', 'Plain Image (either XIP or Load-to-RAM)')#
- IMAGE_TYPES = ['xip', 'load-to-ram', 'Internal flash (XIP)', 'External flash (XIP)', 'Internal Flash (XIP)', 'External Flash (XIP)', 'RAM', 'ram']#
-
app:
Optional[bytes]#
- property app_len: int#
Compute application data length.
The method iterates through all mixins and accumulates their individual application data lengths to determine the total final image data length.
- Returns:
Final image data length in bytes.
-
app_table:
Optional[MultipleImageTable]#
-
cert_block:
Union[CertBlockV1,CertBlockV21,CertBlockVx,None]#
-
collect_data:
Callable[[],BinaryImage]#
- classmethod create_mbi_class(name, family)#
Create Master Boot Image class dynamically.
This method creates a new MBI class by combining the base MasterBootImage class with appropriate mixins based on the configuration stored in the database for the specified family and class name.
- Parameters:
name (
str) – Name of the MBI class to createfamily (
FamilyRevision) – Chip family revision for database lookup
- Raises:
SPSDKValueError – When the specified MBI class name is not supported
- Return type:
Type[Self]- Returns:
Dynamically created Master Boot Image class
-
disassemble_image:
Callable[[bytes],None]#
-
encrypt:
Callable[[BinaryImage,bool],BinaryImage]#
- export()#
Export final bootable image.
- Return type:
bytes- Returns:
Bootable image in bytes.
- export_image()#
Export final bootable image.
The method processes the MBI image through a complete pipeline: validates input data, collects raw image data, optionally encrypts the image, applies post-encryption updates, optionally signs the image, and finalizes it into a bootable format.
- Return type:
- Returns:
Final bootable image ready for deployment.
-
finalize:
Callable[[BinaryImage,bool],BinaryImage]#
- get_config(data_path='./')#
Create configuration file and its data files from the MBI class.
The method generates a configuration dictionary by collecting settings from all mixins and adding MBI-specific configuration values including family, target, and authentication information.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary with MBI settings.
- classmethod get_image_type(family, data)#
Get image type from MBI data and family.
The method retrieves the image type either from a fixed configuration in the database or dynamically determines it using the appropriate IVT mixin class based on the family.
- Parameters:
family (
FamilyRevision) – Device family revision to fetch configuration from database.data (
bytes) – Raw MBI binary data to analyze for image type.
- Return type:
int- Returns:
Integer representation of the image type.
- classmethod get_mbi_class(config)#
Get Master Boot Image class based on configuration.
This method validates the configuration and determines the appropriate MBI class based on the image type, target family, execution target, and authentication type.
- Parameters:
config (
dict[str,Any]) – Configuration dictionary containing image parameters including outputImageExecutionTarget and outputImageAuthenticationType.- Raises:
SPSDKUnsupportedImageType – When image type is not supported or when memory target and authentication combination is not supported for the specified family.
- Return type:
Type[Self]- Returns:
MBI Class type for the specified configuration.
- classmethod get_mbi_classes(family)#
Get all Master Boot Image supported classes for chip family.
The method retrieves MBI classes for all supported target and authentication combinations for the specified chip family from the database configuration.
- Parameters:
family (
FamilyRevision) – Chip family to get MBI classes for.- Raises:
SPSDKValueError – The invalid family.
- Return type:
dict[str,tuple[Type[Self],str,str]]- Returns:
Dictionary with key like image name and values are Tuple with it’s MBI Class and target and authentication type.
- classmethod get_validation_schemas(family)#
Create the validation schema for current image type.
The method builds a comprehensive validation schema by combining family-specific schemas, image type configurations, and mixin schemas. It dynamically updates execution targets and authentication types based on the family’s supported configurations.
- Parameters:
family (
FamilyRevision) – Family description containing revision and chip information.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the image type.
- classmethod get_validation_schemas_basic()#
Create the validation family schema for current image type.
The method retrieves the general schema file, updates the family validation schema with supported families for the current class, and returns it as a list.
- Return type:
list[dict[str,Any]]- Returns:
List containing the family validation schema dictionary.
- classmethod get_validation_schemas_from_cfg(config)#
Get validation schemas based on configuration.
This method retrieves the appropriate MBI class from configuration, validates the basic schemas, loads family revision information, and returns the complete validation schemas for the specific family.
- Parameters:
config (
Config) – Valid configuration object containing MBI settings and family information.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the specified family.
- classmethod hash()#
Generate unique identifier for MasterBootImage class based on mixins.
Creates acronyms from base class names by removing common prefixes/suffixes and generating abbreviations from remaining words.
- Return type:
str- Returns:
Acronym for each MBI base class separated by “-”
- classmethod load_from_config(config)#
Load configuration from dictionary.
Creates an MBI instance from configuration data by determining the appropriate MBI class based on family information and applying mixin configurations.
- Parameters:
config (
Config) – Configuration object containing MBI settings and family information.- Return type:
Self- Returns:
Configured MBI instance of the appropriate class type.
- classmethod parse(data, family=Unknown, Revision: latest, dek=None)#
Parse the final image to individual fields.
This method performs reverse engineering of an MBI image by detecting the appropriate MBI class type, parsing mixins in dependency order, and then reversing the image creation process (finalize, sign, post-encrypt, encrypt operations) to extract the original components.
- Parameters:
data (
bytes) – Final Image in bytesfamily (
FamilyRevision) – Device family revision for MBI class detectiondek (
Optional[str]) – The decryption key for encrypted images
- Raises:
SPSDKParsingError – Cannot determinate the decoding class
- Return type:
Self- Returns:
MBI parsed class instance with extracted image components
-
post_encrypt:
Callable[[BinaryImage,bool],BinaryImage]#
- property rkth: bytes | None#
Get Root Key Table Hash from certificate block if present.
The method extracts the Root Key Table Hash from the certificate block if it exists and is of supported type (CertBlockV1 or CertBlockV21).
- Returns:
Root Key Table Hash as bytes if certificate block is present and valid, None otherwise.
-
sign:
Callable[[BinaryImage,bool],BinaryImage]#
- property total_len: int#
Compute Master Boot Image total data length.
The method iterates through all available mixins and calculates their individual lengths to determine the final combined image data length.
- Returns:
Total length of the Master Boot Image data in bytes.
- property total_length_for_cert_block: int#
Compute total length for certificate block in Master Boot Image.
The method iterates through all mixins and sums up lengths of those that should be counted in legacy certificate block length calculation.
- Returns:
Total length of certificate block data in bytes.
- validate()#
Validate the setting of image.
Iterates through all available mixins and calls their validation methods to ensure the image configuration is correct and complete.
- Raises:
SPSDKError – If any mixin validation fails or image settings are invalid.
- Return type:
None
- spsdk.image.mbi.mbi.mbi_generate_config_templates(family)#
Generate all possible MBI configuration templates for selected family.
The method retrieves all available Master Boot Image classes for the specified family and generates configuration templates for each one. If no MBI classes are found for the family, an empty dictionary is returned.
- Parameters:
family (
FamilyRevision) – Family revision specification for template generation.- Return type:
dict[str,str]- Returns:
Dictionary mapping template names to their configuration content.
Master Boot Image - miscellaneous functions#
SPSDK image processing miscellaneous utilities.
This module provides various helper functions for image data manipulation, including hexadecimal formatting, data reading operations, and dictionary comparison utilities used across SPSDK image processing components.
- spsdk.image.misc.dict_diff(main, mod)#
Calculate the difference between two dictionaries.
Compares two dictionaries and returns a new dictionary containing only the values from the modified dictionary that differ from the main dictionary. Keys that are not present in the main dictionary are skipped. Supports nested dictionaries and handles both numeric and non-numeric value comparisons.
- Parameters:
main (
dict) – The reference dictionary to compare against.mod (
dict) – The modified dictionary containing potential changes.
- Return type:
dict- Returns:
Dictionary containing only the differing values from mod dictionary.
- spsdk.image.misc.hexdump_fmt(data, tab=4, length=16, sep=':')#
Format binary data as hexadecimal dump with configurable layout.
Creates a formatted hexadecimal representation of binary data with customizable indentation, line length, and byte separators for debugging and display purposes.
- Parameters:
data (
bytes) – Binary data to be formatted as hexadecimal dump.tab (
int) – Number of spaces for indentation at the beginning of each line.length (
int) – Number of bytes to display per line before wrapping.sep (
str) – Separator character to place between hexadecimal byte values.
- Return type:
str- Returns:
Formatted hexadecimal string representation of the input data.
- spsdk.image.misc.modulus_fmt(modulus, tab=4, length=15, sep=':')#
Format modulus bytes into a human-readable hexadecimal string representation.
The method prepends a null byte to the modulus and formats it using hexdump formatting with customizable tabulation, line length, and separator characters.
- Parameters:
modulus (
bytes) – The modulus bytes to be formatted.tab (
int) – Number of spaces for indentation, defaults to 4.length (
int) – Maximum number of bytes per line, defaults to 15.sep (
str) – Separator character between hex values, defaults to “:”.
- Return type:
str- Returns:
Formatted hexadecimal string representation of the modulus.
- spsdk.image.misc.read_raw_data(stream, length, index=None, no_seek=False)#
Read raw data from a stream at specified position.
Reads a specified number of bytes from the given stream, optionally seeking to a specific position first. Provides error handling for insufficient data and stream read failures.
- Parameters:
stream (
Union[BufferedReader,BytesIO]) – Input stream to read data from (BufferedReader or BytesIO).length (
int) – Number of bytes to read from the stream.index (
Optional[int]) – Optional position to seek to before reading. If None, reads from current position.no_seek (
bool) – If True, seeks back to original position after reading.
- Raises:
SPSDKError – If index or length parameters are negative.
SPSDKStreamReadFailed – If the stream read operation fails.
SPSDKNotEnoughBytesException – If insufficient bytes are available to read.
- Return type:
bytes- Returns:
Raw bytes data read from the stream.
Master Boot Image - mixin classes#
SPSDK Master Boot Image mixin classes and utilities.
This module provides a comprehensive set of mixin classes for building and exporting Master Boot Images (MBI) across different NXP MCU families. It includes mixins for handling various MBI components like TrustZone, certificates, encryption, signing, and hardware-specific features.
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixin#
Bases:
objectMBI Export Mixin for Master Boot Image processing.
This mixin class provides the core functionality for exporting and processing Master Boot Images (MBI) across different NXP MCU families. It defines the standard workflow for image creation including data collection, encryption, signing, and disassembly operations.
- Variables:
family – Target MCU family and revision for the MBI operations.
- collect_data()#
Collect basic data to create image.
This method creates a basic binary image with a general name as a foundation for image creation in the MBI (Master Boot Image) context.
- Return type:
- Returns:
Collected raw binary image with default configuration.
- disassemble_image(image)#
Disassemble image to individual parts from image.
This method parses the provided image bytes and extracts its constituent components for further processing or analysis.
- Parameters:
image (
bytes) – Raw image data to be disassembled into individual parts.- Return type:
None
- encrypt(image, revert=False)#
Encrypt image if needed.
This method provides a base implementation for image encryption. In the base class, it returns the image unchanged. Subclasses should override this method to implement actual encryption functionality.
- Parameters:
image (
BinaryImage) – Input raw image to encrypt.revert (
bool) – Revert the operation if possible.
- Return type:
- Returns:
Encrypted image or original image if no encryption is applied.
-
family:
FamilyRevision#
- finalize(image, revert=False)#
Finalize the image for export.
This method performs final processing steps on the image before export, which may include adding HMAC authentication, KeyStore data, or other security-related components.
- Parameters:
image (
BinaryImage) – Input binary image to be finalized.revert (
bool) – Flag to revert the finalization operation if supported.
- Return type:
- Returns:
Finalized binary image ready for export.
- post_encrypt(image, revert=False)#
Perform optional post-encryption image modifications.
This method allows for additional processing of the encrypted image data after the main encryption operation has been completed. By default, it returns the image unchanged, but can be overridden in subclasses.
- Parameters:
image (
BinaryImage) – The encrypted binary image to be processed.revert (
bool) – If True, attempt to revert previous post-encryption operations.
- Return type:
- Returns:
The processed binary image, potentially modified.
- sign(image, revert=False)#
Sign image using signature or CRC verification.
This method provides a unified interface for signing binary images across different MBI (Master Boot Image) implementations. The actual signing behavior depends on the specific MBI type and configuration.
- Parameters:
image (
BinaryImage) – Binary image data to be signed.revert (
bool) – If True, attempts to revert the signing operation when supported.
- Return type:
- Returns:
Binary image with applied signature or CRC, or unchanged if no signing required.
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinApp#
Bases:
Mbi_ExportMixinMBI Export Mixin for application data handling.
This mixin class provides functionality for collecting and processing application data in Master Boot Image (MBI) format, including support for Boot Configuration Area (BCA) and Flash Configuration Field (FCF) components.
- Variables:
APP_BLOCK_NAME – Name identifier for the application block.
APP_IMAGE_NAME – Name identifier for the application image.
- APP_BLOCK_NAME = 'Application Block'#
- APP_IMAGE_NAME = 'Application'#
-
BCA_OFFSET:
int#
-
FCF_OFFSET:
int#
-
app:
Optional[bytes]#
-
app_table:
MultipleImageTable#
-
bca:
Optional[BCA]#
-
clean_ivt:
Callable[[bytes],bytes]#
- collect_data()#
Collect application data including update of BCA and FCF.
The method processes application binary data and integrates Boot Configuration Area (BCA) and Flash Configuration Field (FCF) if present. It handles IVT table updates and creates a structured binary image with proper component separation.
- Raises:
SPSDKError – Application data is missing.
- Return type:
- Returns:
Binary image with updated BCA and FCF components properly positioned.
- disassemble_image(image)#
Disassemble image into individual parts.
The method extracts application data and cleans the IVT (Interrupt Vector Table) if the respective methods are available in the class implementation.
- Parameters:
image (
bytes) – Raw binary image data to be disassembled.- Return type:
None
-
disassembly_app_data:
Callable[[bytes],bytes]#
-
fcf:
Optional[FCF]#
-
ivt_table:
Mbi_MixinIvt#
-
total_len:
int#
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppBcaFcf#
Bases:
Mbi_ExportMixinMBI Export Mixin for application data with BCA and FCF components.
This mixin class handles the export functionality for Master Boot Image (MBI) files that contain application data along with Boot Configuration Area (BCA) and Flash Configuration Field (FCF) components. It provides image layout management, validation, and data assembly for Vx chip boot images with predefined memory offsets and structure.
- Variables:
IMG_DIGEST_OFFSET – Offset for image digest in boot image layout (0x360).
IMG_SIGNATURE_OFFSET – Offset for image signature in boot image layout (0x380).
IMG_BCA_OFFSET – Offset for Boot Configuration Area in boot image layout (0x3C0).
IMG_FCF_OFFSET – Offset for Flash Configuration Field in boot image layout (0x400).
IMG_ISK_OFFSET – Offset for Image Signing Key in boot image layout (0x410).
IMG_ISK_HASH_OFFSET – Offset for ISK hash in boot image layout (0x4A0).
IMG_WPC_ROOT_CA_CERT_HASH_OFFSET – Offset for WPC root CA certificate hash (0x5E0).
IMG_WPC_MFG_CA_CERT_OFFSET – Offset for WPC manufacturing CA certificate (0x600).
IMG_DUK_BLOCK_OFFSET – Offset for Device Unique Key block in boot image layout (0x800).
IMG_DATA_START – Starting offset for application data in boot image layout (0xC00).
- IMG_BCA_OFFSET = 960#
- IMG_DATA_START = 3072#
- IMG_DIGEST_OFFSET = 864#
- IMG_DUK_BLOCK_OFFSET = 2048#
- IMG_FCF_OFFSET = 1024#
- IMG_ISK_HASH_OFFSET = 1184#
- IMG_ISK_OFFSET = 1040#
- IMG_SIGNATURE_OFFSET = 896#
- IMG_WPC_MFG_CA_CERT_OFFSET = 1536#
- IMG_WPC_ROOT_CA_CERT_HASH_OFFSET = 1504#
-
app:
bytes#
-
bca:
BCA#
- check_fcf()#
Validate FCF configuration and verify only lifecycle value has been modified.
This method performs two validations: 1. Verifies the lifecycle value is supported by checking against the enum values defined in the FCF LIFECYCLE register 2. Ensures that no FCF registers other than LIFECYCLE have been modified from their reset values
The FCF (Flash Configuration Field) is a critical security component where typically only the lifecycle value should be changed.
- Raises:
SPSDKError – If the lifecycle value is not supported or if any other FCF register has been modified from its reset value.
- Return type:
None
- collect_data()#
Collect application data and update BCA (if present) and FCF.
The method assembles a complete binary image by extracting and organizing various components from the application data including vector table, image hash, ECC signature, Boot Config Area, Flash Config Field, certificates, and application image. If BCA or FCF objects are available, their exported data is used; otherwise, the original binary data is preserved.
- Raises:
SPSDKError – Application data is missing.
- Return type:
- Returns:
Binary Image with updated BCA (if present) and FCF containing all application components.
- disassemble_image(image)#
Disassemble image into individual parts.
The method extracts and stores the application data from the provided image bytes.
- Parameters:
image (
bytes) – Raw image data to be disassembled into components.- Return type:
None
-
fcf:
FCF#
- property image_size: int#
Calculate the total image size used in Boot Configuration Area (BCA).
The method computes the image size by combining the BCA size (calculated from FCF and BCA offsets) with the application length (from data start to end) and adding the digest offset.
- Returns:
Total image size in bytes including BCA, application data and digest.
-
just_header:
bool#
-
total_len:
int#
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppCertBlockManifest#
Bases:
Mbi_ExportMixinMBI Export Mixin for application data with certification block and manifest.
This mixin handles the collection and assembly of Master Boot Image components including application data, certification blocks, and manifests. It provides functionality to validate component integrity, update IVT tables, and export complete binary images with proper structure for NXP MCU boot processes.
-
app:
Optional[bytes]#
-
app_len:
int#
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
- collect_data()#
Collect application data, Certification Block and Manifest including update IVT.
The method validates that all required components (application data, certification block, and manifest) are present, checks manifest length validity, and verifies hash algorithm consistency between manifest and certificate block. It then creates a binary image with updated IVT, application data, certification block, and manifest. For CRC manifests, the CRC is computed and updated.
- Raises:
SPSDKError – When application data, certification block, or manifest is missing.
SPSDKError – When manifest length is invalid.
- Return type:
- Returns:
Binary image with updated IVT and added Certification Block with Manifest.
-
data_to_sign:
Optional[bytes]#
- disassemble_image(image)#
Disassemble image into individual parts.
The method extracts application data from the image by removing certificate block if present and cleaning the IVT table. It also processes application data through disassembly if the method is available.
- Parameters:
image (
bytes) – Binary image data to be disassembled.- Raises:
SPSDKError – If image disassembly fails due to invalid format.
- Return type:
None
-
disassembly_app_data:
Callable[[bytes],bytes]#
- finalize(image, revert=False)#
Finalize the image for export by adding manifest hash.
The method adds a calculated hash to the image based on the manifest’s digest hash algorithm when the digest present flag is set. The operation can be reverted by removing the hash from the end of the image.
- Parameters:
image (
BinaryImage) – Input binary image to be finalized.revert (
bool) – If True, removes the hash from the image instead of adding it.
- Return type:
- Returns:
Finalized binary image with hash appended or removed.
-
ivt_table:
Mbi_MixinIvt#
-
manifest:
Optional[TypeVar(T_Manifest,MasterBootImageManifest,MasterBootImageManifestDigest,MasterBootImageManifestCrc)]#
-
total_len:
int#
-
app:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZone#
Bases:
Mbi_ExportMixinAppMBI Export Mixin for application data with TrustZone support.
This mixin extends the basic application export functionality to handle TrustZone configuration and data processing for NXP MCU images.
- Variables:
TRUST_ZONE_IMAGE_NAME – Default name for TrustZone preset data section.
- TRUST_ZONE_IMAGE_NAME = 'TrustZone Preset data'#
- collect_data()#
Collect application data and TrustZone including update IVT.
The method extends the parent’s collect_data functionality by appending custom TrustZone data when configured. If TrustZone is set to CUSTOM type, the exported TrustZone binary is added to the collected image data.
- Return type:
- Returns:
Image with updated IVT and added TrustZone data if applicable.
- disassemble_image(image)#
Disassemble image to individual parts and extract TrustZone configuration.
The method analyzes the image to determine TrustZone type and extracts the TrustZone configuration if present. It handles enabled, custom, and disabled TrustZone types appropriately before calling the parent disassemble method.
- Parameters:
image (
bytes) – Binary image data to be disassembled.- Return type:
None
-
family:
FamilyRevision#
-
tz_type:
TrustZoneType#
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlock#
Bases:
Mbi_ExportMixinMBI Export Mixin for application data with TrustZone and certification block support.
This mixin class handles the export and assembly of Master Boot Image (MBI) components including application data, TrustZone settings, and certification blocks. It manages the collection and organization of these components into a complete binary image with proper IVT updates and alignment requirements.
-
app:
Optional[bytes]#
-
app_len:
int#
-
app_table:
MultipleImageTable#
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
- collect_data()#
Collect application data and TrustZone including update IVT.
The method assembles the complete Master Boot Image by combining the application data, certificate block, optional relocation table, and TrustZone settings. It updates the IVT (Interrupt Vector Table) with proper addresses and lengths before creating the final binary image structure.
- Raises:
SPSDKError – Application data or Certificate block is missing.
SPSDKError – Unsupported certificate block type (only CertBlockV1 supported).
- Return type:
- Returns:
Complete binary image with updated IVT and all required components.
- disassemble_image(image)#
Disassemble image into individual components.
Parses the input image and extracts its components including TrustZone configuration, certificate blocks, and application data. Updates the object’s trust_zone and app attributes based on the parsed data.
- Parameters:
image (
bytes) – Binary image data to be disassembled.- Return type:
None
-
disassembly_app_data:
Callable[[bytes],bytes]#
-
family:
FamilyRevision#
-
ivt_table:
Mbi_MixinIvt#
-
total_len:
int#
-
total_length_for_cert_block:
int#
-
tz_type:
TrustZoneType#
-
app:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlockEncrypt#
Bases:
Mbi_ExportMixinMBI Export Mixin for encrypted application data with TrustZone and certification block support.
This mixin extends the base MBI export functionality to handle encrypted application images that include TrustZone configurations and certification blocks. It manages the collection, encryption, and disassembly of MBI images with CertBlockV1 support and various TrustZone types including custom configurations.
- Variables:
HMAC_OFFSET – Offset for HMAC calculation in the image structure.
-
HMAC_OFFSET:
int#
-
app:
Optional[bytes]#
-
app_len:
int#
-
app_table:
MultipleImageTable#
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
- collect_data()#
Collect application data and TrustZone including update IVT.
The method assembles the final binary image by updating the IVT table with application data, optionally adding relocation table and TrustZone settings based on configuration.
- Raises:
SPSDKError – Application data or Certificate block is missing.
SPSDKError – Certificate block is not CertBlockV1 type.
- Return type:
- Returns:
Binary image with updated IVT and optionally added TrustZone settings.
-
ctr_init_vector:
bytes#
- disassemble_image(image)#
Disassemble image into individual components.
The method parses the image to extract TrustZone configuration, application data, and other components. It handles different TrustZone types (enabled, custom) and processes the image accordingly by removing TrustZone data and cleaning the IVT.
- Parameters:
image (
bytes) – Binary image data to be disassembled.- Return type:
None
-
disassembly_app_data:
Callable[[bytes],bytes]#
- encrypt(image, revert=False)#
Encrypt or decrypt image data using AES-CTR algorithm.
The method performs AES-CTR encryption/decryption on the provided image data using HMAC key and initialization vector. When revert is True, it decrypts the image. The encryption key may be derived from the HMAC key depending on key store configuration.
- Parameters:
image (
BinaryImage) – Input binary image to encrypt or decrypt.revert (
bool) – If True, decrypt the image instead of encrypting it.
- Raises:
SPSDKError – When HMAC key or initialization vector is missing.
- Return type:
- Returns:
New BinaryImage containing encrypted or decrypted data.
-
hmac_key:
Optional[bytes]#
- property img_len: int#
Get image length of encrypted legacy image.
Calculates the total length including the base image, certificate block signature, encrypted IVT, and initialization vector.
- Raises:
SPSDKError – When certification block is missing.
- Returns:
Total image length in bytes including all components.
-
ivt_table:
Mbi_MixinIvt#
- post_encrypt(image, revert=False)#
Perform post-encryption image updates and restructuring.
This method reorganizes the encrypted image by updating the IVT table with new offsets and lengths, then reconstructs the image with proper block ordering including the certification block and initialization vector. Can also revert the operation to restore the original encrypted image structure.
- Parameters:
image (
BinaryImage) – The encrypted binary image to be processed.revert (
bool) – If True, reverts the post-encryption changes to restore original structure.
- Raises:
SPSDKError – If certification block is missing or not CertBlockV1 type.
- Return type:
- Returns:
Restructured encrypted image with updated layout and blocks.
-
total_len:
int#
-
tz_type:
TrustZoneType#
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneCertBlockV2#
Bases:
Mbi_ExportMixinExport Mixin for MBI images with application data, TrustZone and Certification Block V21.
This mixin provides functionality to collect and disassemble MBI (Master Boot Image) components including application data, TrustZone configuration, and Certification Block V21. It handles the assembly of these components into a complete binary image with proper IVT (Interrupt Vector Table) updates and supports disassembly of existing images back into individual components.
-
app:
Optional[bytes]#
-
app_len:
int#
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
- collect_data()#
Collect application data, Certification Block and Manifest including update IVT.
The method combines application data with certification block and optional trust zone data into a single binary image. The IVT (Interrupt Vector Table) is updated with proper lengths and addresses before creating the final image structure.
- Raises:
SPSDKError – When either application data or certification block is missing.
- Return type:
- Returns:
Binary image containing updated IVT, application data, certification block, and optional trust zone data.
-
data_to_sign:
Optional[bytes]#
- disassemble_image(image)#
Disassemble image into individual parts.
The method extracts application data from the image by removing certificate block if present and cleaning the IVT table. It also processes application data through disassembly if the method is available.
- Parameters:
image (
bytes) – Binary image data to be disassembled.- Raises:
SPSDKError – If image disassembly fails or image format is invalid.
- Return type:
None
-
disassembly_app_data:
Callable[[bytes],bytes]#
-
ivt_table:
Mbi_MixinIvt#
-
total_len:
int#
-
tz_type:
TrustZoneType#
-
app:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTrustZoneV2#
Bases:
Mbi_ExportMixinAppTrustZoneExport Mixin for handling application data with TrustZone version 2 support.
This class extends the base TrustZone mixin to specifically handle TrustZone V2 format, providing enhanced data collection and image disassembly capabilities with proper 4-byte alignment requirements for TrustZone V2 operations.
- collect_data()#
Collect application data and TrustZone configuration into a binary image.
This method gathers the application and TrustZone data, ensures proper 4-byte alignment for TrustZone V2, and updates the IVT table with correct offsets when TrustZone is enabled. The TrustZone offset is stored in the application’s CRC location.
- Raises:
SPSDKError – When TrustZone image is not found but trust_zone is enabled.
SPSDKError – When Application image is not found but trust_zone is enabled.
- Return type:
- Returns:
Binary image containing collected application and TrustZone data.
- disassemble_image(image)#
Disassemble image into individual parts and extract TrustZone configuration.
The method parses the image to identify TrustZone type from IVT table and extracts TrustZone block if present. For custom TrustZone type, it locates and parses the TrustZone block, then continues with standard image disassembly.
- Parameters:
image (
bytes) – Binary image data to be disassembled.- Raises:
SPSDKError – Cannot find TrustZone block when custom TrustZone type is detected.
- Return type:
None
-
trust_zone:
Optional[TrustZoneV2]#
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinAppTzCrcAhab#
Bases:
Mbi_ExportMixinMBI export mixin for application data with TrustZone, CRC checksum and AHAB container.
This mixin handles the collection and organization of Master Boot Image (MBI) data that includes application binary, optional TrustZone configuration, CRC-32 checksum validation, and AHAB (Advanced High Assurance Boot) container for secure boot operations. It manages the proper layout and offset calculations for all components within the final boot image.
- Variables:
CRC_IMAGE_NAME – Name identifier for CRC checksum section in the image.
AHAB_IMAGE_NAME – Name identifier for AHAB container section in the image.
- AHAB_IMAGE_NAME = 'AHAB Container'#
- CRC_IMAGE_NAME = 'CRC-32 MPEG checksum'#
-
ahab:
AHABContainerV2#
-
app:
bytes#
- collect_data()#
Collect application data and TrustZone including update IVT.
This method assembles a complete MBI (Master Boot Image) by collecting application data, TrustZone configuration, CRC records, and AHAB container. It updates the IVT table with proper offsets and configures the AHAB image array entries with relative offsets to the AHAB container.
- Return type:
- Returns:
Binary image containing the complete MBI structure with all components properly aligned and configured.
-
crc_check_record:
Optional[ImageArrayEntryV2]#
- disassemble_image(image)#
Disassemble image into individual components.
This method parses the provided image and extracts its constituent parts using both AHAB export functionality and TrustZone v2 mixing capabilities.
- Parameters:
image (
bytes) – Binary image data to be disassembled.- Return type:
None
-
image_version:
int#
-
ivt_table:
Mbi_MixinIvt#
- sign(image, revert=False)#
Sign the image with CRC calculation and AHAB signature.
Performs CRC32-MPEG calculation over the image data (excluding the CRC block itself) and updates the AHAB (Advanced High Assurance Boot) container with proper signatures and hash values. The method also logs SRK (Super Root Key) hash information for verification purposes.
- Parameters:
image (
BinaryImage) – Input binary image to be signed.revert (
bool) – If True, returns the original image without modifications.
- Return type:
- Returns:
Signed binary image with updated CRC and AHAB signature block.
-
total_len:
int#
-
trust_zone:
TrustZoneV2#
-
tz_type:
TrustZoneType#
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinCrcSign#
Bases:
Mbi_ExportMixinMBI Export Mixin for CRC-based signing operations.
This mixin class provides CRC-based signing functionality for Master Boot Image (MBI) export operations. It implements MPEG2 CRC32 calculation over image data and updates the IVT table with the computed CRC value for image integrity verification.
- Variables:
IVT_CRC_CERTIFICATE_OFFSET – Offset in IVT table where CRC value is stored.
update_crc_val_cert_offset – Callable to update CRC value at certificate offset.
-
IVT_CRC_CERTIFICATE_OFFSET:
int#
- sign(image, revert=False)#
Sign binary image with CRC32 checksum.
Calculates CRC32 using MPEG2 specification over the entire image data except for the 4-byte CRC field at the certificate offset in the IVT table, then updates the image with the calculated CRC value.
- Parameters:
image (
BinaryImage) – Input binary image to be signed with CRC.revert (
bool) – If True, returns original image without CRC calculation.
- Return type:
- Returns:
Binary image with updated CRC32 checksum in IVT table.
- Raises:
SPSDKError – Invalid CRC offset in the image.
-
update_crc_val_cert_offset:
Callable[[bytes,int],bytes]#
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinCrcSignBca#
Bases:
Mbi_ExportMixinMBI Export Mixin for CRC-based signing in Boot Configuration Area.
This mixin provides functionality to sign Master Boot Images using CRC32 checksum calculation and embedding the signature information into the Boot Configuration Area (BCA). The mixin calculates CRC32-MPEG checksum of the application data and updates the BCA registers with CRC parameters including start address, byte count, and expected value.
-
IMG_DATA_START:
int#
-
app:
bytes#
-
bca:
BCA#
-
image_size:
int#
- sign(image, revert=False)#
Calculate CRC32 for image data and update Boot Config Area.
The method computes CRC32-MPEG checksum for the image data starting from IMG_DATA_START offset and updates the Boot Config Area registers with CRC parameters and expected value.
- Parameters:
image (
BinaryImage) – Input binary image to be signed with CRC.revert (
bool) – If True, returns original image without CRC calculation.
- Raises:
SPSDKError – When Boot Config Area is not initialized.
- Return type:
- Returns:
Binary image with updated Boot Config Area containing CRC information.
-
IMG_DATA_START:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinCrcSignEnd#
Bases:
Mbi_ExportMixinMBI Export Mixin for CRC signature handling at image end.
This mixin provides functionality to sign Master Boot Images by calculating and appending a CRC32 checksum at the end of the image data. It handles both signing operations and revert operations for CRC-based image authentication.
-
ivt_table:
Mbi_MixinIvt#
- sign(image, revert=False)#
Sign binary image with CRC32 checksum.
Calculates CRC32-MPEG checksum for the binary image data and appends it to the image. Updates the IVT table total length to include the CRC. Can also revert the signing process by removing the last 4 bytes (CRC) from the image.
- Parameters:
image (
BinaryImage) – Binary image to be signed with CRC checksum.revert (
bool) – If True, removes the CRC from image instead of adding it.
- Raises:
SPSDKError – Application image not found in the binary image.
- Return type:
- Returns:
Binary image with appended CRC checksum or with CRC removed if revert is True.
-
ivt_table:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinEccSign#
Bases:
Mbi_ExportMixinExport Mixin for ECC signature operations in MBI images.
This mixin provides functionality to add and remove ECC signatures from MBI (Master Boot Image) binary images. It handles the signature calculation process using configurable signature providers and certificate blocks, supporting both signing operations and signature reversion for testing purposes.
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
-
data_to_sign:
Optional[bytes]#
- sign(image, revert=False)#
Calculate ECC signature and return updated image with signature.
The method either adds an ECC signature to the end of the image or reverts the operation by removing the signature from the image.
- Parameters:
image (
BinaryImage) – Input raw binary image to be signed or unsigned.revert (
bool) – If True, removes signature from image; if False, adds signature.
- Raises:
SPSDKError – Certificate block or image is missing for revert operation.
SPSDKError – Unsupported certificate block type (only CertBlockV21 supported).
SPSDKError – Signature provider is missing for signing operation.
- Return type:
- Returns:
Image with ECC signature appended or signature removed.
-
signature_provider:
Optional[SignatureProvider]#
-
cert_block:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinEccSignVx#
Bases:
Mbi_ExportMixinMBI Export Mixin for ECC signature handling.
This mixin provides ECC signature functionality for Master Boot Image (MBI) export operations. It handles the complete signing process including image digest calculation, ECC signature generation, and certificate block integration for secure boot images.
- Variables:
IMG_DIGEST_OFFSET – Offset position for image digest in the binary layout.
IMG_BCA_OFFSET – Offset position for Boot Configuration Area in the binary layout.
IMG_FCF_OFFSET – Offset position for Flash Configuration Field in the binary layout.
IMG_DATA_START – Starting position of image data in the binary layout.
-
IMG_BCA_OFFSET:
int#
-
IMG_DATA_START:
int#
-
IMG_DIGEST_OFFSET:
int#
-
IMG_FCF_OFFSET:
int#
-
add_hash:
bool#
-
app:
Optional[bytes]#
-
bca:
BCA#
-
cert_block:
CertBlockVx#
-
image_size:
int#
- sign(image, revert=False)#
Calculate ECC signature and digest for the image.
The method updates the Boot Config Area with image size, calculates hash from specific image sections, generates ECC signature, and enriches the image with signature data and certificates.
- Parameters:
image (
BinaryImage) – Input raw binary image to be signed.revert (
bool) – If True, returns original image without signing.
- Return type:
- Returns:
Image enriched by ECC signature, SHA256 digest and certificates.
- Raises:
SPSDKError – When signature provider is missing or unable to get signature.
-
signature_provider:
Optional[SignatureProvider]#
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinHmacKeyStoreFinalize#
Bases:
Mbi_ExportMixinMBI Export Mixin for HMAC and KeyStore finalization.
This mixin provides functionality to finalize Master Boot Image (MBI) exports by computing and embedding HMAC authentication values and optionally including KeyStore data. It handles both standard finalization and revert operations, managing binary image structure including sub-image splitting when HMAC data needs to be inserted at specific offsets.
-
HMAC_OFFSET:
int#
-
HMAC_SIZE:
int#
-
compute_hmac:
Callable[[bytes],bytes]#
- finalize(image, revert=False)#
Finalize the image for export by adding HMAC and optionally KeyStore.
The method processes the input image to add HMAC authentication and optional KeyStore data. When reverting, it removes previously added HMAC and KeyStore sections. During normal operation, it computes HMAC for the image data and inserts it at the designated offset, splitting existing sub-images if necessary.
- Parameters:
image (
BinaryImage) – Input binary image to be finalized.revert (
bool) – If True, removes HMAC and KeyStore from the image instead of adding them.
- Raises:
SPSDKError – Invalid image structure when splitting sub-images.
- Return type:
- Returns:
Finalized binary image with HMAC and optional KeyStore added or removed.
-
ivt_table:
Mbi_MixinIvt#
-
HMAC_OFFSET:
- class spsdk.image.mbi.mbi_mixin.Mbi_ExportMixinRsaSign#
Bases:
Mbi_ExportMixinMBI Export Mixin for RSA signature operations.
This mixin provides RSA signature functionality for Master Boot Image (MBI) export operations, including signature generation and verification capabilities with support for different certificate block versions.
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
- sign(image, revert=False)#
Calculate RSA signature and return updated image with signature.
The method either adds an RSA signature to the end of the image or reverts the operation by removing the signature from the image.
- Parameters:
image (
BinaryImage) – Input raw image to be signed or unsigned.revert (
bool) – Revert the operation by removing signature if True.
- Raises:
SPSDKError – Certificate block or image is missing for revert operation.
SPSDKError – Only CertBlockV1 is supported for revert operation.
SPSDKError – Signature provider is missing for signing operation.
- Return type:
- Returns:
Image with RSA signature appended or signature removed.
-
signature_provider:
Optional[SignatureProvider]#
-
cert_block:
- class spsdk.image.mbi.mbi_mixin.Mbi_Mixin#
Bases:
objectBase class for Master Boot Image Mixin classes.
This class provides the foundation for implementing modular components that can be mixed into Master Boot Image configurations. Each mixin represents a specific functionality or data section that contributes to the final boot image structure.
- Variables:
VALIDATION_SCHEMAS – List of schema names used for configuration validation.
NEEDED_MEMBERS – Dictionary of required member variables for the mixin.
PRE_PARSED – List of pre-parsed configuration fields.
COUNT_IN_LEGACY_CERT_BLOCK_LEN – Flag indicating if mixin counts in legacy certificate block length.
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
bool= True#
-
NEEDED_MEMBERS:
dict[str,Any] = {}#
-
PRE_PARSED:
list[str] = []#
-
VALIDATION_SCHEMAS:
list[str] = []#
-
family:
FamilyRevision#
- mix_app_len()#
Compute application data length of individual mixin.
This method returns the default application data length for an atomic mixin, which is zero for the base implementation.
- Return type:
int- Returns:
Application data length of atomic Mixin in bytes.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str) – Output folder to store files.- Return type:
dict[str,Any]- Returns:
Dictionary containing mixin configuration data.
- classmethod mix_get_validation_schemas(family)#
Get validation schemas from mixin.
The method retrieves validation schemas for MBI (Master Boot Image) configuration based on the class’s VALIDATION_SCHEMAS attribute.
- Parameters:
family (
FamilyRevision) – Family revision to get schemas for.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries.
- mix_init()#
Initialize the mixin component.
This method sets up the initial state and configuration for the mixin functionality within the MBI (Master Boot Image) context.
- Return type:
None
- mix_len()#
Compute length of individual mixin.
- Return type:
int- Returns:
Length of atomic Mixin in bytes.
- mix_load_from_config(config)#
Load configuration of mixin from dictionary.
- Parameters:
config (
Config) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary data to individual fields.
This method takes binary data representing a final image and parses it into the individual fields of the MBI (Master Boot Image) structure.
- Parameters:
data (
bytes) – Final Image in bytes to be parsed.- Return type:
None
- mix_validate()#
Validate the setting of image.
Performs validation checks on the current image configuration to ensure all settings are properly configured and consistent.
- Raises:
SPSDKError – Invalid image configuration or settings.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinAhab#
Bases:
Mbi_MixinMaster Boot Image AHAB mixin class.
This mixin provides AHAB (Advanced High-Assurance Boot) container support for Master Boot Images, including validation schemas, configuration management, and CRC check functionality for secure boot operations across NXP MCU portfolio.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for AHAB configuration.
NEEDED_MEMBERS – Required member dictionary specifying AHAB container dependency.
-
FEATURE:
str#
-
NEEDED_MEMBERS:
dict[str,Any] = {'ahab': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['ahab_sign_support', 'ahab_sign_support_add_image_hash_type', 'ahab_sign_support_add_core_id']#
-
ahab:
AHABContainerV2#
-
app:
bytes#
-
app_crc:
bool#
- property crc_check_record: ImageArrayEntryV2 | None#
Check if CRC is included in AHAB container.
This method examines the AHAB (Advanced High-Assurance Boot) container to determine if it contains a CRC check record as its last image array entry. The CRC record is used to verify data integrity of the boot image.
- Returns:
The CRC check image array entry if present, otherwise None.
-
image_version:
int#
-
ivt_table:
Mbi_MixinIvt#
-
load_address:
int#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
Creates a configuration dictionary for the AHAB container with image hash type and core ID settings when multiple options are available.
- Parameters:
output_folder (
str) – Output folder to store files.- Raises:
SPSDKError – When AHAB container is missing.
- Return type:
dict[str,Any]- Returns:
Configuration dictionary with AHAB container settings.
- classmethod mix_get_validation_schemas(family)#
Get validation schemas from mixin.
This method retrieves validation schemas for MBI (Master Boot Image) AHAB (Advanced High Assurance Boot) configuration based on the specified family revision.
- Parameters:
family (
FamilyRevision) – Family revision to get schemas for.- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas dictionaries.
- mix_len()#
Get length of Certificate Block V2.1.
- Raises:
SPSDKError – When certification block or signature provider is missing.
- Return type:
int- Returns:
Length of Certificate Block V2.1.
- mix_load_from_config(config)#
Load configuration from dictionary and initialize AHAB container with image entries.
The method creates an AHAB container with the main application image and optionally adds TrustZone and CRC check images based on configuration settings.
- Parameters:
config (
Config) – Configuration dictionary containing AHAB settings, core ID, and hash type.- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and initialize individual fields.
The method extracts the AHAB container from the binary data at the calculated offset and parses it using the chip configuration. If the instance has an image_version attribute, it updates it with the software version from AHAB.
- Parameters:
data (
bytes) – Final Image in bytes to be parsed.- Raises:
SPSDKError – If AHAB container parsing fails.
SPSDKValueError – If the data format is invalid or corrupted.
- Return type:
None
- mix_validate()#
Validate the setting of image.
Checks if the AHAB container is present in the image configuration.
- Raises:
SPSDKError – When AHAB container is missing from the image.
- Return type:
None
-
tz_type:
TrustZoneType#
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinApp#
Bases:
Mbi_MixinMaster Boot Image Application Mixin.
This mixin class handles application binary data within Master Boot Image (MBI) structures, providing functionality to load, validate, and manage application images for secure boot processes across NXP MCU portfolio.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for configuration validation.
NEEDED_MEMBERS – Required class members with their default values for proper mixin initialization.
-
NEEDED_MEMBERS:
dict[str,Any] = {'_app': b'', 'app_ext_memory_align': 4096}#
-
VALIDATION_SCHEMAS:
list[str] = ['app']#
- property app: bytes#
Get application data.
- Returns:
Raw application data as bytes.
-
app_ext_memory_align:
int#
- load_binary_image_file(path)#
Load binary image from file (S19, HEX, BIN).
The method loads a binary image from the specified file and validates alignment requirements if app_ext_memory_align is configured. The loaded image data is stored in the app attribute.
- Parameters:
path (
str) – Path to the binary image file to load.- Raises:
SPSDKError – If invalid data file is detected or alignment requirements are not met.
- Return type:
None
- mix_app_len()#
Compute application data length of individual mixin.
- Return type:
int- Returns:
Application data length of atomic Mixin.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
The method extracts configuration data from the mixin and optionally writes the application binary to the specified output folder if present.
- Parameters:
output_folder (
str) – Output folder to store the application binary file.- Return type:
dict[str,Any]- Returns:
Dictionary containing the mixin configuration with input image file reference.
- mix_len()#
Get size of plain input application image.
- Return type:
int- Returns:
Length of application in bytes.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Config) – Configuration object containing input file settings.- Raises:
SPSDKError – If the input image file cannot be loaded or is invalid.
- Return type:
None
- mix_validate()#
Validate the application format and interrupt vector table.
Performs validation checks on the application binary to ensure it meets minimum size requirements and has valid interrupt vector table entries. The method verifies that the stack pointer, program counter, and DSC illegal operation vectors are not identical.
- Raises:
SPSDKError – The application format is invalid or minimum size requirements are not met.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinAppCrc#
Bases:
Mbi_MixinMaster Boot Image mixin for CRC application support.
This mixin provides functionality for adding CRC check records to Master Boot Images, enabling application integrity verification during boot process. It manages CRC configuration and validation schemas for AHAB signing operations.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas for CRC support.
NEEDED_MEMBERS – Dictionary defining required member variables and defaults.
-
NEEDED_MEMBERS:
dict[str,Any] = {'app_crc': False}#
-
VALIDATION_SCHEMAS:
list[str] = ['ahab_sign_support_add_crc']#
-
app_crc:
bool#
-
crc_check_record:
Optional[ImageArrayEntryV2]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str) – Output folder to store files.- Return type:
dict[str,Any]- Returns:
Dictionary containing mixin configuration with CRC check settings.
- mix_len()#
Get length of mix-in data.
The method returns the length of additional data that needs to be included in the image based on whether application CRC is enabled.
- Return type:
int- Returns:
Length of mix-in data in bytes (4 if app_crc is enabled, 0 otherwise).
- mix_load_from_config(config)#
Load configuration from dictionary.
The method loads the CRC check configuration setting from the provided configuration dictionary and sets the app_crc attribute accordingly.
- Parameters:
config (
Config) – Configuration dictionary containing MBI settings.- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinBca#
Bases:
Mbi_MixinMaster Boot Image BCA mixin class.
This mixin provides Boot Configuration Area (BCA) functionality for Master Boot Images, handling BCA parsing, configuration loading, and validation operations.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas required for BCA operations.
NEEDED_MEMBERS – Dictionary defining required member variables for the mixin.
BCA_OFFSET – Memory offset where BCA data is located in the image.
- BCA_OFFSET = 960#
-
NEEDED_MEMBERS:
dict[str,Any] = {'bca': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['bca']#
-
app:
bytes#
-
bca:
Optional[BCA]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
The method generates configuration data for the mixin, including BCA (Boot Configuration Area) settings if present. When BCA is configured, it writes the BCA configuration to a YAML file in the specified output folder.
- Parameters:
output_folder (
str) – Output folder to store configuration files.- Return type:
dict[str,Any]- Returns:
Dictionary containing configuration data with file references.
- classmethod mix_get_validation_schemas(family)#
Get validation schemas from BCA mixin.
Creates validation schemas for Boot Configuration Array (BCA) settings that can be used in configuration files. The schemas support three input formats: nested dictionary, YAML file path, or binary file path.
- Parameters:
family (
FamilyRevision) – Family revision to get schemas for.- Return type:
list[dict[str,Any]]- Returns:
List containing validation schema dictionary for BCA configuration.
- mix_len()#
Get length of BCA.
- Return type:
int- Returns:
Length of BCA in bytes, or 0 if BCA is not present.
- mix_load_from_config(config)#
Load configuration from dictionary and update BCA settings.
The method loads default BCA configuration from the application and then updates it based on the provided configuration. It supports three formats: direct dictionary configuration, YAML sub-configuration, or binary file.
- Parameters:
config (
Config) – Configuration object containing BCA settings in various formats.- Raises:
SPSDKError – When BCA binary file has invalid size.
SPSDKTypeError – When configuration format is invalid.
- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and initialize individual MBI fields.
The method attempts to parse the Boot Configuration Area (BCA) from the provided binary data at the predefined offset. If parsing fails, the BCA field is set to None.
- Parameters:
data (
bytes) – Binary data containing the Master Boot Image to be parsed.- Raises:
SPSDKError – When BCA parsing fails due to invalid or corrupted data.
- Return type:
None
- mix_validate()#
Validate the settings of the MBI image.
This method performs validation checks on the image configuration, specifically verifying that the BCA (Boot Configuration Area) is properly formatted if present.
- Raises:
SPSDKError – Configuration of BCA is invalid.
- Return type:
None
-
total_len:
int#
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockV1#
Bases:
Mbi_MixinMaster Boot Image certification block V1 mixin.
This mixin provides functionality for handling Certificate Block V1 operations in Master Boot Images, including configuration loading, validation, and export capabilities for secure boot implementations.
- Variables:
VALIDATION_SCHEMAS – Configuration validation schema names.
NEEDED_MEMBERS – Required member variables for mixin functionality.
-
HMAC_SIZE:
int#
-
NEEDED_MEMBERS:
dict[str,Any] = {'cert_block': None, 'signature_provider': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['cert_block_v1', 'signer']#
-
cert_block:
Optional[CertBlockV1]#
-
get_key_store_presented:
Callable[[bytes],int]#
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
The method generates a YAML configuration file for the certificate block and returns a configuration dictionary containing the certificate block filename and signer information.
- Parameters:
output_folder (
str) – Output folder to store the generated configuration files.- Raises:
SPSDKError – Certificate block is missing.
- Return type:
dict[str,Any]- Returns:
Configuration dictionary with certificate block filename and signer details.
- mix_len()#
Get length of Certificate Block V1.
- Return type:
int- Returns:
Length of Certificate Block V1 in bytes, or 0 if no certificate block exists.
- mix_load_from_config(config)#
Load configuration from dictionary.
Loads certificate block and signature provider from the provided configuration.
- Parameters:
config (
Config) – Configuration dictionary containing certificate block and signature provider settings.- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and initialize individual MBI fields.
This method parses the provided binary data to extract certificate block information, calculates the appropriate offset based on HMAC and key store presence, and initializes the certificate block and signature provider fields.
- Parameters:
data (
bytes) – Complete MBI binary image data to be parsed.- Raises:
SPSDKError – If the certificate block parsing fails.
- Return type:
None
- mix_validate()#
Validate the setting of image.
This method checks that the certificate block is present and is of type CertBlockV1, verifies that a signature provider is defined, and validates that the signature provider can work with the public key from the last certificate in the chain.
- Raises:
SPSDKError – Certificate block is missing, not CertBlockV1 type, or signature provider is not defined.
- Return type:
None
-
signature_provider:
Optional[SignatureProvider]#
-
total_len:
int#
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockV21#
Bases:
Mbi_MixinMaster Boot Image certification block V2.1 mixin class.
This mixin provides functionality for handling certification blocks version 2.1 in Master Boot Images, including configuration management, validation, and signature provider integration.
- Variables:
VALIDATION_SCHEMAS – Configuration validation schema names.
NEEDED_MEMBERS – Required member variables for mixin functionality.
-
NEEDED_MEMBERS:
dict[str,Any] = {'cert_block': None, 'signature_provider': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['cert_block_v21', 'signer']#
-
cert_block:
Optional[CertBlockV21]#
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
The method generates a YAML configuration file for the certificate block and returns a configuration dictionary with the certificate block filename and signer information.
- Parameters:
output_folder (
str) – Output folder to store the generated configuration files.- Raises:
SPSDKError – Certificate block is missing.
- Return type:
dict[str,Any]- Returns:
Configuration dictionary containing certificate block filename and signer info.
- mix_len()#
Get length of Certificate Block V2.1.
The method calculates the total length by combining the expected size of the certificate block and the signature length from the signature provider.
- Raises:
SPSDKError – When certification block or signature provider is missing.
- Return type:
int- Returns:
Length of Certificate Block V2.1.
- mix_load_from_config(config)#
Load configuration from dictionary.
The method initializes certificate block and signature provider from the provided configuration data.
- Parameters:
config (
Config) – Dictionary with configuration fields.- Raises:
SPSDKError – Invalid configuration data or missing required fields.
- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and initialize individual certificate fields.
This method extracts the certificate block from the provided binary data using the IVT table offset and initializes the signature provider to None.
- Parameters:
data (
bytes) – Complete binary image data containing certificate information.- Raises:
SPSDKError – If certificate block parsing fails or data is invalid.
- Return type:
None
- mix_validate()#
Validate the settings of the MBI image.
This method verifies that the certification block and signature provider are properly configured, and ensures that the signature provider’s public key matches the key from either the ISK certificate or the root key record.
- Raises:
SPSDKError – When certification block is missing, signature provider is missing, or when the signature provider’s public key verification fails.
- Return type:
None
-
signature_provider:
Optional[SignatureProvider]#
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinCertBlockVx#
Bases:
Mbi_MixinMaster Boot Image certification block mixin for MC55xx family devices.
This mixin provides certification block functionality for Master Boot Images, including configuration loading, validation, and binary parsing capabilities. It manages certificate blocks, signature providers, and related settings for secure boot operations on MC55xx devices.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for configuration.
NEEDED_MEMBERS – Dictionary defining required member attributes.
-
IMG_ISK_OFFSET:
int#
-
NEEDED_MEMBERS:
dict[str,Any] = {'cert_block': None, 'signature_provider': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['cert_block_vX', 'signer', 'just_header']#
-
add_hash:
bool#
-
cert_block:
CertBlockVx#
-
just_header:
bool#
- mix_load_from_config(config)#
Load configuration from dictionary.
This method initializes the MBI mixin with configuration data including certificate block, signature provider, and various flags.
- Parameters:
config (
Config) – Dictionary with configuration fields containing certificate block data, signature provider settings, addCertHash flag, and justHeader flag.- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and initialize individual MBI fields.
This method extracts the certificate block from the provided binary data and resets the signature provider to prepare for further processing.
- Parameters:
data (
bytes) – Complete MBI binary image data in bytes format.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – Signature provider is missing.
- Return type:
None
-
signature_provider:
Optional[SignatureProvider]#
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinCtrInitVector#
Bases:
Mbi_MixinMaster Boot Image mixin for encryption counter initialization vector management.
This mixin provides functionality for handling counter initialization vectors used in encryption operations within Master Boot Images. It manages the generation, validation, and configuration of counter initial vectors with support for both user-specified and randomly generated values.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas for this mixin.
NEEDED_MEMBERS – Required member variables with default values.
PRE_PARSED – List of pre-parsed configuration elements.
-
HMAC_SIZE:
int#
-
NEEDED_MEMBERS:
dict[str,Any] = {'_ctr_init_vector': b'\xfb\x819\x8aI\x00\x06\xdd[\xf9\x05\xbfdr\x7f\t'}#
-
PRE_PARSED:
list[str] = ['cert_block']#
-
VALIDATION_SCHEMAS:
list[str] = ['ctr_init_vector']#
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
- property ctr_init_vector: bytes | None#
Get counter initialization vector.
- Returns:
Counter initialization vector bytes if set, None otherwise.
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str) – Output folder to store files.- Raises:
AssertionError – When CTR initialization vector is not bytes type.
- Return type:
dict[str,Any]- Returns:
Dictionary containing mixin configuration with CTR initialization vector.
- mix_load_from_config(config)#
Load configuration from dictionary.
The method initializes the CTR initialization vector from the provided configuration. If ‘CtrInitVector’ is present in config, it loads the symmetric key with the required size.
- Parameters:
config (
Config) – Configuration object containing fields for MBI setup.- Raises:
SPSDKError – If the CTR initialization vector cannot be loaded properly.
- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and populate individual MBI fields.
This method extracts the CTR initialization vector from the binary data by calculating its offset based on certificate block, HMAC, and key store positions within the image.
- Parameters:
data (
bytes) – Complete MBI binary image data to parse.- Raises:
AssertionError – If cert_block is not an instance of CertBlockV1.
- Return type:
None
- mix_validate()#
Validate the setting of image.
The method validates that the counter initialization vector exists and has the correct size for encryption counter operations.
- Raises:
SPSDKError – Initial vector for encryption counter doesn’t exist or has invalid size.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinFcf#
Bases:
Mbi_MixinMaster Boot Image FCF mixin class.
This mixin class provides FCF (Flash Configuration Field) functionality for Master Boot Images, handling FCF data parsing, configuration loading, and validation. The FCF contains critical flash configuration settings that must be properly configured for device operation.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas used for FCF configuration.
NEEDED_MEMBERS – Dictionary defining required FCF member attributes.
FCF_OFFSET – Standard offset position for FCF data in flash memory.
- FCF_OFFSET = 1024#
-
NEEDED_MEMBERS:
dict[str,Any] = {'fcf': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['fcf']#
-
app:
bytes#
-
fcf:
Optional[FCF]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
This method extracts the FCF (Flash Configuration Field) configuration, writes it to a YAML file in the specified output folder, and returns a configuration dictionary containing the filename reference.
- Parameters:
output_folder (
str) – Output folder path where the FCF YAML file will be stored.- Return type:
dict[str,Any]- Returns:
Configuration dictionary with FCF filename reference.
- classmethod mix_get_validation_schemas(family)#
Get validation schemas from FCF mixin.
This method constructs validation schemas for Flash Configuration Field (FCF) settings, supporting multiple input formats including nested dictionaries, YAML files, and binary files.
- Parameters:
family (
FamilyRevision) – Family revision to get schemas for.- Return type:
list[dict[str,Any]]- Returns:
List containing validation schema dictionary for FCF configuration.
- mix_len()#
Get length of FCF.
- Return type:
int- Returns:
Length of FCF in bytes, or 0 if FCF is not present.
- mix_load_from_config(config)#
Load configuration from dictionary.
The method loads FCF (Flash Configuration Field) configuration from various sources: - Direct dictionary configuration - YAML configuration file - Binary FCF file First loads default FCF from application, then updates with provided configuration.
- Parameters:
config (
Config) – Configuration object with FCF fields and search paths.- Raises:
SPSDKError – Invalid FCF binary file size or configuration errors.
SPSDKTypeError – Type mismatch in configuration data.
- Return type:
None
- mix_parse(data)#
Parse the binary data to individual fields.
This method extracts and parses the FCF (Flash Configuration Field) from the provided binary data at the predefined offset.
- Parameters:
data (
bytes) – Final image binary data to be parsed.- Raises:
SPSDKError – If FCF parsing fails or data is invalid.
- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – Configuration of FCF is invalid.
- Return type:
None
-
total_len:
int#
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinFwVersion#
Bases:
Mbi_MixinMaster Boot Image Firmware Version Mixin.
This mixin class provides firmware version management functionality for Master Boot Images, handling configuration loading and retrieval of firmware version information.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas used for firmware version validation.
NEEDED_MEMBERS – Dictionary defining required members for the mixin functionality.
-
NEEDED_MEMBERS:
dict[str,Any] = {'manifest': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['firmware_version']#
-
firmware_version:
Optional[int]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str) – Output folder to store files.- Return type:
dict[str,Any]- Returns:
Dictionary containing mixin configuration with firmware version.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Config) – Dictionary with configuration fields.- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinHmac#
Bases:
Mbi_MixinMaster Boot Image HMAC mixin class.
This mixin provides HMAC (Hash-based Message Authentication Code) functionality for Master Boot Images, enabling secure authentication and integrity verification of boot images.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas supported by this mixin.
HMAC_OFFSET – Offset in the image where the HMAC table is located.
HMAC_SIZE – Size of HMAC table in bytes.
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
bool= False#
- HMAC_OFFSET = 64#
- HMAC_SIZE = 32#
-
NEEDED_MEMBERS:
dict[str,Any] = {'_hmac_key': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['hmac']#
- compute_hmac(data)#
Compute HMAC hash for the provided data.
The method uses the stored HMAC key to generate a hash-based message authentication code. If no HMAC key is available, returns empty bytes.
- Parameters:
data (
bytes) – Data to be hashed.- Raises:
SPSDKError – Invalid size of HMAC result.
- Return type:
bytes- Returns:
Result HMAC hash of input data, or empty bytes if no HMAC key is set.
-
dek:
Optional[str]#
- property hmac_key: bytes | None#
Get HMAC key in bytes.
- Returns:
HMAC key as bytes if available, None otherwise.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str) – Output folder to store files.- Return type:
dict[str,Any]- Returns:
Dictionary containing mixin configuration with encryption key information.
- mix_len()#
Get length of HMAC block.
The method returns the HMAC block size if an HMAC key is present, otherwise returns 0.
- Return type:
int- Returns:
Length of HMAC block in bytes, or 0 if no HMAC key is configured.
- mix_load_from_config(config)#
Load configuration from dictionary.
This method initializes the HMAC key from the configuration. If an output image encryption key file is specified in the config, it loads the symmetric key with the expected HMAC size.
- Parameters:
config (
Config) – Configuration object containing fields for MBI setup.- Raises:
SPSDKError – If the encryption key file cannot be loaded or has invalid size.
- Return type:
None
- mix_parse(data)#
Parse the binary data to individual fields.
The method extracts and processes HMAC key from DEK if available.
- Parameters:
data (
bytes) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
Validates that the HMAC key, if present, has the correct length of 32 bytes.
- Raises:
SPSDKError – Invalid HMAC key length.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinHmacMandatory#
Bases:
Mbi_MixinHmacMaster Boot Image HMAC mixin with mandatory key validation.
This mixin extends the base HMAC functionality by enforcing that an HMAC key must be present during validation. It provides stricter validation rules for scenarios where HMAC authentication is required rather than optional.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for mandatory HMAC.
-
VALIDATION_SCHEMAS:
list[str] = ['hmac_mandatory']#
- mix_validate()#
Validate the setting of image.
Checks if HMAC key exists and performs additional validation through parent class.
- Raises:
SPSDKError – If HMAC key is missing or other validation errors occur.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinHwKey#
Bases:
Mbi_MixinMaster Boot Image hardware key user mode enablement mixin.
This mixin provides functionality for managing hardware key user mode settings in Master Boot Images, including configuration loading, validation, and binary parsing of hardware key enablement flags.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for this mixin.
NEEDED_MEMBERS – Default values for required mixin members.
-
NEEDED_MEMBERS:
dict[str,Any] = {'user_hw_key_enabled': False}#
-
VALIDATION_SCHEMAS:
list[str] = ['hw_key']#
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str) – Output folder to store files.- Return type:
dict[str,Any]- Returns:
Dictionary containing mixin configuration with hardware user mode keys setting.
- mix_load_from_config(config)#
Load configuration from dictionary.
The method loads hardware user mode keys enablement setting from the provided configuration dictionary.
- Parameters:
config (
Config) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
This method extracts hardware key enablement information from the provided binary data using the IVT table.
- Parameters:
data (
bytes) – Final Image in bytes.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – Invalid HW key enabled member type.
- Return type:
None
-
user_hw_key_enabled:
Optional[bool]#
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinImageSubType#
Bases:
Mbi_MixinMaster Boot Image SubType mixin class.
This mixin provides functionality for managing image subtypes in Master Boot Images, supporting different subtype configurations for various NXP MCU families including KW45xx, K32W1xx, and MCXN9xx series.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for image subtype.
NEEDED_MEMBERS – Dictionary defining required members with default values.
- class Mbi_ImageSubTypeKw45xx(tag, label, description=None)#
Bases:
SpsdkEnumMBI image subtype enumeration for KW45xx and K32W1xx MCU families.
This enumeration defines the supported image subtypes for Master Boot Image (MBI) format used in KW45xx and K32W1xx microcontrollers, including main application and NBU (Narrowband Unit) image types.
- MAIN = (0, 'MAIN', 'Default (main) application image')#
- NBU = (1, 'NBU', 'NBU (Narrowband Unit) image')#
- class Mbi_ImageSubTypeMcxn9xx(tag, label, description=None)#
Bases:
SpsdkEnumMBI image subtype enumeration for MCXN9xx devices.
This enumeration defines the supported image subtypes for MCXN9xx series microcontrollers, including main application and recovery image types.
- MAIN = (0, 'MAIN', 'Default (main) application image')#
- RECOVERY = (1, 'RECOVERY', 'Recovery image')#
-
NEEDED_MEMBERS:
dict[str,Any] = {'image_subtype': 0}#
-
VALIDATION_SCHEMAS:
list[str] = ['image_subtype']#
-
image_subtype:
Optional[int]#
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str) – Output folder to store files.- Raises:
SPSDKError – When the image subtype is not defined.
- Return type:
dict[str,Any]- Returns:
Dictionary containing the mixin configuration with output image subtype.
- mix_load_from_config(config)#
Load configuration from dictionary.
The method loads the output image subtype from the provided configuration, defaulting to “main” if not specified.
- Parameters:
config (
Config) – Configuration object containing the settings to load.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
This method extracts the image subtype from the provided binary data using the IVT (Interrupt Vector Table) and stores it in the image_subtype attribute.
- Parameters:
data (
bytes) – Final Image in bytes to be parsed.- Return type:
None
- set_image_subtype(image_subtype)#
Set image subtype for MBI mixin.
Converts string representation of image subtype to integer value using appropriate enum table based on the target MCU family and stores it in the class instance.
- Parameters:
image_subtype (
Union[str,int,None]) – Image subtype as string name, integer value, or None for default.- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinImageVersion#
Bases:
Mbi_MixinMaster Boot Image version management mixin.
This mixin provides functionality for handling image version information in Master Boot Images, including loading version data from configuration, parsing version from binary data, and managing version-related operations through the IVT table.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas used for image version validation.
NEEDED_MEMBERS – Dictionary defining required members with default values.
image_version_to_image_type – Flag indicating if image version maps to image type.
-
NEEDED_MEMBERS:
dict[str,Any] = {'image_version': 0}#
-
VALIDATION_SCHEMAS:
list[str] = ['image_version']#
-
image_version:
Optional[int]#
-
image_version_to_image_type:
bool= True#
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
- Parameters:
output_folder (
str) – Output folder to store files.- Return type:
dict[str,Any]- Returns:
Dictionary containing mixin configuration with image version.
- mix_load_from_config(config)#
Load configuration from dictionary.
- Parameters:
config (
Config) – Dictionary with configuration fields.- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and set individual image fields.
This method extracts the image version from the provided binary data using the IVT (Interrupt Vector Table) and stores it in the image_version attribute.
- Parameters:
data (
bytes) – Complete binary image data to be parsed.- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinIvt#
Bases:
Mbi_MixinMaster Boot Image Interrupt Vector Table mixin class.
This mixin provides functionality for handling IVT (Interrupt Vector Table) operations in Master Boot Images, including flag management, offset definitions, and IVT table manipulation for NXP MCU boot images.
- Variables:
IVT_IMAGE_LENGTH_OFFSET – Offset for image length field in IVT table.
IVT_IMAGE_FLAGS_OFFSET – Offset for image flags field in IVT table.
IVT_CRC_CERTIFICATE_OFFSET – Offset for CRC certificate field in IVT table.
IVT_LOAD_ADDR_OFFSET – Offset for load address field in IVT table.
-
IMAGE_TYPE:
MbiImageTypeEnum#
- IVT_CRC_CERTIFICATE_OFFSET = 40#
- IVT_IMAGE_FLAGS_IMAGE_TYPE_MASK = 63#
- IVT_IMAGE_FLAGS_IMG_VER_MASK = 65535#
- IVT_IMAGE_FLAGS_IMG_VER_SHIFT = 16#
- IVT_IMAGE_FLAGS_OFFSET = 36#
- IVT_IMAGE_FLAGS_SUB_TYPE_MASK = 3#
- IVT_IMAGE_FLAGS_SUB_TYPE_SHIFT = 6#
- IVT_IMAGE_FLAGS_TZ_TYPE_MASK = 3#
- IVT_IMAGE_FLAGS_TZ_TYPE_SHIFT = 13#
- IVT_IMAGE_LENGTH_OFFSET = 32#
- IVT_LOAD_ADDR_OFFSET = 52#
-
app_table:
Optional[MultipleImageTable]#
- classmethod check_total_length(data)#
Check total length field from raw MBI image data.
Validates that the input data contains sufficient bytes for a valid MBI image by checking both the minimum IVT table size and comparing the declared image length with actual data size.
- Parameters:
data (
bytes) – Raw MBI image data to validate.- Raises:
SPSDKParsingError – Insufficient length of image has been detected.
- Return type:
None
- clean_ivt(app_data)#
Clean IVT table from added information.
The method removes specific fields from the IVT (Interrupt Vector Table) by zeroing out the image length, flags, CRC/certificate offset, and execution address fields.
- Parameters:
app_data (
bytes) – Application data that should be cleaned.- Return type:
bytes- Returns:
Cleaned application image with zeroed IVT fields.
- create_flags()#
Create flags of image.
Constructs image type flags by combining base image type with optional features like TrustZone type, image subtype, hardware key enablement, key store presence, relocation table, and boot image version.
- Raises:
SPSDKError – When image subtype is not defined but required.
- Return type:
int- Returns:
Combined image type flags as integer value.
- classmethod get_app_table_presented(data)#
Get the Multiple Application table present flag from raw data.
- Parameters:
data (
bytes) – Raw MBI image data.- Return type:
int- Returns:
True if Multiple Application table is included, False otherwise.
- classmethod get_cert_block_offset(data)#
Get the certificate block offset from raw data.
The method validates the total length of the data and extracts the certificate block offset from the MBI image data.
- Parameters:
data (
bytes) – Raw MBI image data to extract certificate block offset from.- Return type:
int- Returns:
Certificate block offset value.
- classmethod get_cert_block_offset_from_data(data)#
Get the certificate block offset from raw MBI image data.
This method extracts the certificate block offset from the IVT (Interrupt Vector Table) section of the MBI image data using little-endian byte order.
- Parameters:
data (
bytes) – Raw MBI image data containing the IVT structure.- Return type:
int- Returns:
Certificate block offset as integer value.
- classmethod get_flags(data)#
Get the Image flags from raw data.
The method extracts flags from MBI image data and validates the total length during the process.
- Parameters:
data (
bytes) – Raw MBI image data.- Raises:
SPSDKError – Invalid data length or format.
- Return type:
int- Returns:
Image flags value.
- classmethod get_flags_from_data(data)#
Get the Image flags from raw data.
Extracts the image flags from the specified offset in the MBI image data using little-endian byte order.
- Parameters:
data (
bytes) – Raw MBI image data as bytes.- Return type:
int- Returns:
Image flags as integer value.
- classmethod get_hw_key_enabled(data)#
Get the HW key enabled setting from raw data.
This method extracts and checks the hardware key enablement flag from the provided MBI image data by analyzing the flags field.
- Parameters:
data (
bytes) – Raw MBI image data as bytes.- Return type:
bool- Returns:
True if hardware key is enabled, False otherwise.
- classmethod get_image_type(data)#
Get the Image type from raw data.
Extracts the image type by applying the image type mask to the flags obtained from the raw MBI data.
- Parameters:
data (
bytes) – Raw MBI image data as bytes.- Return type:
int- Returns:
Image type as integer value.
- classmethod get_image_version(data)#
Get the Image firmware version from raw data.
Extracts the firmware version from the MBI image flags by checking the version flag and applying appropriate bit shifts and masks to retrieve the version value.
- Parameters:
data (
bytes) – Raw MBI image data as bytes.- Return type:
int- Returns:
Firmware version as integer, returns 0 if version flag is not set.
- classmethod get_key_store_presented(data)#
Get the KeyStore present flag from raw data.
- Parameters:
data (
bytes) – Raw MBI image data.- Return type:
int- Returns:
True if KeyStore is included, False otherwise.
- classmethod get_load_address(data)#
Get the load address from raw MBI image data.
The method validates the total length of the data before extracting the load address.
- Parameters:
data (
bytes) – Raw MBI image data to extract load address from.- Return type:
int- Returns:
Load address value extracted from the MBI image data.
- classmethod get_load_address_from_data(data)#
Get the load address from raw MBI image data.
Extracts the load address from the Interrupt Vector Table (IVT) at the predefined offset within the provided raw MBI image data.
- Parameters:
data (
bytes) – Raw MBI image data containing the IVT structure.- Return type:
int- Returns:
Load address as integer value extracted from the IVT.
- classmethod get_sub_type(data)#
Get the Image sub type from raw data.
Extracts the sub type information from the image flags field in the raw MBI data by applying appropriate bit shifting and masking operations.
- Parameters:
data (
bytes) – Raw MBI image data.- Return type:
int- Returns:
Image sub type as integer value.
- classmethod get_tz_type(data)#
Get the Image TrustZone type settings from raw data.
- Parameters:
data (
bytes) – Raw MBI image data.- Return type:
int- Returns:
TrustZone type.
-
image_subtype:
Optional[int]#
-
image_version:
Optional[int]#
-
image_version_to_image_type:
bool#
- property ivt_table: Self#
Get IVT table itself.
Returns the current mixin IVT object instance for method chaining or direct access.
- Returns:
Current mixin IVT object.
-
load_address:
Optional[int]#
-
tz_type:
Optional[TrustZoneType]#
- update_crc_val_cert_offset(app_data, crc_val_cert_offset)#
Update CRC/Certificate offset field value in binary data.
This method modifies the CRC/Certificate offset field at a specific position in the provided binary data using little-endian byte order.
- Parameters:
app_data (
bytes) – Input binary array to be modified.crc_val_cert_offset (
int) – New CRC/Certificate offset value to set.
- Return type:
bytes- Returns:
Updated binary array with modified CRC/Certificate offset field.
- update_ivt(app_data, total_len, crc_val_cert_offset=0)#
Update IVT table in application image.
The method modifies the Interrupt Vector Table (IVT) fields including image flags, load address, image length, and CRC/certificate offset in the provided application data.
- Parameters:
app_data (
bytes) – Application data that should be modified.total_len (
int) – Total length of bootable image.crc_val_cert_offset (
int) – CRC value or Certification block offset.
- Return type:
bytes- Returns:
Updated whole application image.
- update_total_length(app_data, total_length)#
Update total length field in the IVT table.
This method modifies the application data by updating the image length field in the Interrupt Vector Table (IVT) at the predefined offset.
- Parameters:
app_data (
bytes) – Application data containing the IVT table to be modified.total_length (
int) – New total length value to be written to the IVT.
- Return type:
bytes- Returns:
Modified application data with updated total length field.
-
user_hw_key_enabled:
Optional[bool]#
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinIvtZeroTotalLength#
Bases:
Mbi_MixinIvtMaster Boot Image Interrupt Vector table mixin for XIP images with zero total length.
This mixin class extends the base IVT functionality to handle XIP (Execute In Place) images that require the total length field in the IVT to be set to zero, regardless of the actual image size. It provides specialized handling for images that don’t need length validation during boot process.
- classmethod check_total_length(data)#
Check total length field from raw data.
Validates that the total length field in the MBI image header matches or is compatible with the actual data length provided.
- Parameters:
data (
bytes) – Raw MBI image data to validate.- Raises:
SPSDKParsingError – Insufficient length of image has been detected.
- Return type:
None
- update_ivt(app_data, total_len, crc_val_cert_offset=0)#
Update IVT table in application image.
This method overrides the parent implementation by setting the total length to 0, effectively ignoring the provided total_len parameter as indicated by the debug log.
- Parameters:
app_data (
bytes) – Application data that should be modified.total_len (
int) – Total length of bootable image (will be ignored and set to 0).crc_val_cert_offset (
int) – CRC value or Certification block offset.
- Return type:
bytes- Returns:
Updated whole application image with modified IVT table.
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinKeyStore#
Bases:
Mbi_MixinMaster Boot Image KeyStore mixin class.
This mixin provides KeyStore functionality for Master Boot Image operations, handling keystore file loading, configuration management, and validation for secure boot processes.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas used for keystore validation.
NEEDED_MEMBERS – Dictionary defining required member variables for the mixin.
COUNT_IN_LEGACY_CERT_BLOCK_LEN – Flag indicating if keystore counts in legacy certificate block length calculation.
-
COUNT_IN_LEGACY_CERT_BLOCK_LEN:
bool= False#
-
HMAC_OFFSET:
int#
-
HMAC_SIZE:
int#
-
NEEDED_MEMBERS:
dict[str,Any] = {'_hmac_key': None, 'key_store': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['key_store']#
-
hmac_key:
Optional[bytes]#
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
The method exports key store data to a binary file in the specified output folder and returns configuration dictionary with the file reference.
- Parameters:
output_folder (
str) – Output folder to store the key store file.- Return type:
dict[str,Any]- Returns:
Configuration dictionary containing keyStoreFile path or None if no key store exists.
- mix_len()#
Get length of KeyStore block.
The method calculates the length of the exported KeyStore data if a KeyStore is present and configured with KEYSTORE source type, otherwise returns 0.
- Return type:
int- Returns:
Length of KeyStore block in bytes, or 0 if no KeyStore or different source type.
- mix_load_from_config(config)#
Load configuration from dictionary.
This method initializes the key store from the configuration if a keyStoreFile is specified in the config.
- Parameters:
config (
Config) – Configuration object containing setup fields including optional keyStoreFile.- Raises:
SPSDKError – If the keystore file cannot be loaded or is invalid.
- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and initialize individual MBI fields.
The method examines the binary data to determine if a key store is present and initializes the key_store attribute accordingly. If a key store is found, it extracts the key store data from the appropriate offset in the binary.
- Parameters:
data (
bytes) – Complete MBI binary image data to be parsed.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – When KeyStore is used but HMAC key is not provided.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinLoadAddress#
Bases:
Mbi_MixinMaster Boot Image load address mixin.
This mixin handles the management of load addresses for Master Boot Images, providing functionality to load, configure, and parse execution addresses from configuration data and binary image data.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for load address configuration.
-
VALIDATION_SCHEMAS:
list[str] = ['load_addr']#
-
ivt_table:
Mbi_MixinIvt#
-
load_address:
Optional[int]#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
The method retrieves configuration data including the output image execution address based on the load address. The load address must be defined before calling this method.
- Parameters:
output_folder (
str) – Output folder to store files.- Raises:
SPSDKError – The load address is not defined.
- Return type:
dict[str,Any]- Returns:
Dictionary containing mixin configuration with execution address.
- mix_load_from_config(config)#
Load configuration from dictionary.
The method extracts the output image execution address from the provided configuration and sets the load_address attribute.
- Parameters:
config (
Config) – Configuration object containing MBI settings.- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
This method extracts the load address from the provided binary data using the IVT table and stores it in the load_address attribute.
- Parameters:
data (
bytes) – Final Image in bytes containing the binary data to be parsed.- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifest#
Bases:
Mbi_MixinTrustZoneMandatoryMaster Boot Image Manifest mixin class.
This mixin provides manifest management functionality for Master Boot Images, including manifest creation, validation, and binary parsing capabilities. It extends trust zone mandatory functionality with firmware versioning and certificate block handling.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas required for this mixin.
NEEDED_MEMBERS – Dictionary of required member variables and their defaults.
PRE_PARSED – List of members that need pre-parsing during configuration.
-
NEEDED_MEMBERS:
dict[str,Any] = {'cert_block': None, 'family': 'Unknown', 'manifest': None, 'revision': 'latest', 'trust_zone': None}#
-
PRE_PARSED:
list[str] = ['cert_block']#
-
VALIDATION_SCHEMAS:
list[str] = ['trust_zone_mandatory', 'firmware_version']#
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
-
firmware_version:
Optional[int]#
-
ivt_table:
Mbi_MixinIvt#
-
manifest:
Optional[MasterBootImageManifest]#
- manifest_class#
alias of
MasterBootImageManifest
- mix_len()#
Get length of Manifest block.
- Raises:
SPSDKError – The Image manifest must exist.
- Return type:
int- Returns:
Length of Manifest block.
- mix_load_from_config(config)#
Load configuration from dictionary.
This method loads configuration settings from the provided config object, sets the firmware version, and initializes the manifest with the current firmware version and trust zone settings.
- Parameters:
config (
Config) – Configuration object containing the settings to load.- Raises:
SPSDKValueError – If configuration contains invalid values.
- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and initialize individual MBI fields.
The method extracts the manifest from the binary data using the certificate block and IVT table offsets, then initializes firmware version and trust zone properties from the parsed manifest data.
- Parameters:
data (
bytes) – Complete MBI binary image data to be parsed.- Raises:
AssertionError – If cert_block is not an instance of CertBlockV21.
- Return type:
None
- mix_validate()#
Validate the settings of the MBI image.
This method performs validation checks on the image configuration, ensuring that all required components are properly set, including the mandatory manifest.
- Raises:
SPSDKError – The image manifest is missing or the configuration is invalid.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifestCrc#
Bases:
Mbi_MixinManifestMaster Boot Image Manifest mixin with CRC support.
This mixin extends the base manifest functionality to include CRC-based Master Boot Image manifest handling, providing firmware version management and trust zone configuration.
- Variables:
manifest_class – Reference to MasterBootImageManifestCrc class.
-
manifest:
Optional[MasterBootImageManifestCrc]#
- manifest_class#
alias of
MasterBootImageManifestCrc
- mix_load_from_config(config)#
Load configuration from dictionary.
Loads the firmware version from configuration and initializes the manifest with the specified firmware version and trust zone settings.
- Parameters:
config (
Config) – Configuration object containing the settings to load.- Raises:
SPSDKValueError – If configuration contains invalid values.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinManifestDigest#
Bases:
Mbi_MixinManifestMaster Boot Image Manifest mixin for devices supporting ImageDigest functionality.
This mixin extends the base manifest functionality to handle image digest operations for Master Boot Images on devices that support digest validation. It manages manifest creation with configurable hash algorithms and provides digest-aware length calculations.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names required for this manifest type.
-
VALIDATION_SCHEMAS:
list[str] = ['trust_zone_mandatory', 'firmware_version']#
-
manifest:
Optional[MasterBootImageManifestDigest]#
- manifest_class#
alias of
MasterBootImageManifestDigest
- mix_get_config(output_folder)#
Get the configuration of the mixin.
The method retrieves the mixin configuration including firmware version and validates that the image manifest exists before processing.
- Parameters:
output_folder (
str) – Output folder to store files.- Raises:
SPSDKError – The Image manifest must exist.
- Return type:
dict[str,Any]- Returns:
Dictionary containing the mixin configuration with firmware version.
- mix_len()#
Get length of Manifest block.
Calculates the total length of the manifest block including the manifest itself and optional hash digest if present based on the manifest flags.
- Raises:
SPSDKError – If the image manifest does not exist.
- Return type:
int- Returns:
Total length of manifest block in bytes including optional hash.
- mix_load_from_config(config)#
Load configuration from dictionary.
Loads configuration settings and initializes the manifest with firmware version, trust zone settings, and appropriate hash algorithm based on certificate block.
- Parameters:
config (
Config) – Configuration object containing firmware settings and parameters.- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinRelocTable#
Bases:
Mbi_MixinMaster Boot Image Relocation Table Mixin.
This mixin handles relocation table functionality for Master Boot Images, managing multiple image entries with their destination addresses and load flags. It provides configuration loading, validation, and export capabilities for application tables containing relocatable image data.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for this mixin.
NEEDED_MEMBERS – Dictionary of required member variables and their defaults.
-
NEEDED_MEMBERS:
dict[str,Any] = {'_app': None, 'app_table': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['app_table']#
-
app:
Optional[bytes]#
-
app_table:
Optional[MultipleImageTable]#
- disassembly_app_data(data)#
Disassemble application data to extract application and Multiple Application Table.
The method parses the input data to extract a Multiple Application Table if present, and returns the application data portion while storing the table in the class instance.
- Parameters:
data (
bytes) – Raw application data bytes that may contain Multiple Application Table.- Return type:
bytes- Returns:
Application data without Multiple Application Table portion.
- mix_app_len()#
Compute application data length of individual mixin.
The method calculates the length of exported application table data if the table exists, otherwise returns 0.
- Return type:
int- Returns:
Application data length of atomic Mixin in bytes.
- mix_get_config(output_folder)#
Get the configuration of the mixin.
Extracts configuration data from the application table and writes binary files to the specified output folder for each table entry.
- Parameters:
output_folder (
str) – Output folder to store the generated binary files.- Return type:
dict[str,Any]- Returns:
Dictionary containing the mixin configuration with application table data.
- mix_len()#
Get length of additional binaries block.
The method calculates the length by exporting the application table if it exists, otherwise returns 0 for cases where no application table is present.
- Return type:
int- Returns:
Length of additional binaries block in bytes.
- mix_load_from_config(config)#
Load configuration from dictionary.
The method processes the applicationTable configuration section to create a MultipleImageTable with image entries. Each entry contains binary data, destination address, and load type information.
- Parameters:
config (
Config) – Configuration object containing applicationTable section.- Raises:
SPSDKError – Invalid configuration or missing binary files.
- Return type:
None
- mix_validate()#
Validate the setting of image.
This method checks if the application table configuration is valid by ensuring that when an application table exists, it contains at least one entry.
- Raises:
SPSDKError – Application table configuration is invalid - the application relocation table must have at least one record when present.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZone#
Bases:
Mbi_MixinMaster Boot Image TrustZone mixin class.
This mixin provides TrustZone functionality for Master Boot Images, managing TrustZone configuration, validation, and integration with certificate blocks. The class handles both preset and custom TrustZone configurations.
- Variables:
VALIDATION_SCHEMAS – Configuration validation schemas for TrustZone.
NEEDED_MEMBERS – Required class members for TrustZone functionality.
PRE_PARSED – List of pre-parsed configuration elements.
-
NEEDED_MEMBERS:
dict[str,Any] = {'family': 'Unknown', 'revision': 'latest', 'trust_zone': None}#
-
PRE_PARSED:
list[str] = ['cert_block']#
-
VALIDATION_SCHEMAS:
list[str] = ['trust_zone']#
-
cert_block:
Union[CertBlockV1,CertBlockV21,None]#
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
This method generates configuration data for the mixin, including TrustZone settings. If a custom TrustZone configuration is present, it exports the configuration to a binary file in the specified output folder.
- Parameters:
output_folder (
str) – Output folder to store generated configuration files.- Return type:
dict[str,Any]- Returns:
Dictionary containing the mixin configuration with TrustZone settings.
- mix_len()#
Get length of TrustZone array.
The method returns the length of the TrustZone array if it exists and the type is CUSTOM, otherwise returns 0.
- Return type:
int- Returns:
Length of TrustZone array, or 0 if not applicable.
- mix_load_from_config(config)#
Load configuration from dictionary.
Loads TrustZone configuration settings from the provided configuration dictionary. If TrustZone is enabled, either loads preset file or creates default TrustZone instance.
- Parameters:
config (
Config) – Configuration dictionary containing TrustZone settings.- Return type:
None
- mix_parse(data)#
Parse the binary data to extract and initialize TrustZone configuration.
The method analyzes the TrustZone type from the IVT table and initializes the appropriate TrustZone object based on the detected type (enabled, custom, or none).
- Parameters:
data (
bytes) – Final Image in bytes containing the binary data to parse.- Raises:
SPSDKParsingError – Invalid TrustZone type detected in the binary data.
- Return type:
None
- property tz_type: TrustZoneType#
Get the TrustZone configuration type for this MBI.
Determines the TrustZone type based on the current trust_zone configuration. Returns DISABLED if no TrustZone is configured, CUSTOM if a customized configuration exists, or ENABLED for standard TrustZone configuration.
- Returns:
The TrustZone type indicating current configuration state.
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZoneMandatory#
Bases:
Mbi_MixinTrustZoneMaster Boot Image Trust Zone mixin for devices where TrustZone is mandatory.
This mixin extends the base TrustZone functionality to enforce TrustZone configuration for devices that require it. It automatically initializes TrustZone settings and validates that TrustZone configuration is present during image creation.
- Variables:
VALIDATION_SCHEMAS – List of validation schemas used for configuration validation.
-
VALIDATION_SCHEMAS:
list[str] = ['trust_zone_mandatory']#
-
family:
FamilyRevision#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
The method exports trust zone configuration to a binary file if customized and returns the configuration dictionary with the file reference.
- Parameters:
output_folder (
str) – Output folder to store the trust zone binary file.- Return type:
dict[str,Any]- Returns:
Configuration dictionary containing trust zone preset file reference if applicable.
- mix_init()#
Initialize the mixin component.
Sets up the TrustZone configuration if it hasn’t been initialized yet. Creates a new TrustZone instance using the current family setting when trust_zone is None.
- Return type:
None
- mix_load_from_config(config)#
Load configuration from dictionary.
This method processes the configuration to set up TrustZone settings. If a TrustZone preset file is specified, it loads the preset and warns if default values are used. Otherwise, it initializes a default TrustZone configuration for the family.
- Parameters:
config (
Config) – Configuration object containing TrustZone setup parameters.- Return type:
None
- mix_validate()#
Validate the setting of image.
- Raises:
SPSDKError – The TrustZone configuration is invalid.
- Return type:
None
- class spsdk.image.mbi.mbi_mixin.Mbi_MixinTrustZoneV2#
Bases:
Mbi_MixinMaster Boot Image TrustZone version 2 mixin class.
This mixin provides TrustZone version 2 functionality for Master Boot Images, handling configuration, validation, and management of TrustZone security settings for NXP MCU devices.
- Variables:
VALIDATION_SCHEMAS – List of validation schema names for TrustZone v2.
NEEDED_MEMBERS – Required member variables and their default values.
-
NEEDED_MEMBERS:
dict[str,Any] = {'family': 'Unknown', 'revision': 'latest', 'trust_zone': None}#
-
VALIDATION_SCHEMAS:
list[str] = ['trust_zone_2']#
-
ivt_table:
Mbi_MixinIvt#
- mix_get_config(output_folder)#
Get the configuration of the mixin.
Exports trust zone configuration to files and returns configuration dictionary with references to the exported files.
- Parameters:
output_folder (
str) – Output folder to store the exported trust zone files.- Return type:
dict[str,Any]- Returns:
Configuration dictionary containing trust zone preset file reference.
- mix_len()#
Get length of TrustZone array.
- Return type:
int- Returns:
Length of TrustZone array, or 0 if TrustZone is not set.
- mix_load_from_config(config)#
Load configuration from dictionary.
Loads trust zone configuration from the provided config dictionary. If a trust zone preset file is specified, it attempts to load it first as a config file, then falls back to parsing it as a binary file if that fails.
- Parameters:
config (
Config) – Dictionary with configuration fields.- Raises:
SPSDKError – When trust zone configuration cannot be loaded from preset file.
- Return type:
None
- mix_parse(data)#
Parse the binary to individual fields.
This method extracts and validates TrustZone configuration from the binary data, setting up the trust_zone attribute based on the detected TrustZone type.
- Parameters:
data (
bytes) – Final Image in bytes.- Raises:
SPSDKParsingError – Invalid TrustZone type or Trust Zone block not found.
- Return type:
None
-
trust_zone:
Optional[TrustZoneV2]#
- property tz_type: TrustZoneType#
Get the TrustZone type for this MBI.
Determines whether TrustZone is enabled with custom configuration or just enabled with default settings.
- Returns:
TrustZone type indicating custom or enabled configuration.
- spsdk.image.mbi.mbi_mixin.get_all_mbi_mixins()#
Get all classes inheriting from MBI mixin base classes.
This function finds all classes that inherit from any of the specified mixin base classes, including classes that inherit from classes that inherit from these base classes. Only processes modules in the same directory as this module.
- Return type:
dict[str,Type]- Returns:
Dictionary mapping class qualified names to class types of all mixin classes.
Image Exceptions#
SPSDK Image processing exceptions.
This module defines custom exception classes for handling errors that occur during image processing operations, including unsupported image types, segment handling issues, and data stream processing failures.
- exception spsdk.image.exceptions.SPSDKNotEnoughBytesException(desc=None)#
Bases:
SPSDKRawDataExceptionSPSDK exception for insufficient data during raw data reading operations.
This exception is raised when read_raw_data operations cannot read the required amount of data from the source, indicating data truncation or unexpected end of data stream.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.image.exceptions.SPSDKRawDataException(desc=None)#
Bases:
SPSDKErrorException raised when raw data operations fail.
This exception is thrown when SPSDK encounters errors during raw data reading, parsing, or processing operations in image handling workflows.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.image.exceptions.SPSDKSegmentNotPresent(desc=None)#
Bases:
SPSDKErrorSPSDK exception for missing image segments.
This exception is raised when a required segment is not found in an image during processing or validation operations.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.image.exceptions.SPSDKStreamReadFailed(desc=None)#
Bases:
SPSDKRawDataExceptionSPSDK exception for stream reading failures.
This exception is raised when the read_raw_data operation fails to read data from a stream due to various stream-related issues such as corruption, unexpected end of stream, or read access problems.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
- exception spsdk.image.exceptions.SPSDKUnsupportedImageType(desc=None)#
Bases:
SPSDKErrorSPSDK exception for unsupported image types.
This exception is raised when attempting to process an image type that is not supported by the SPSDK image processing functionality.
Initialize the base SPSDK Exception.
- Parameters:
desc (
Optional[str]) – Optional description of the exception.
AHAB Container#
SPSDK AHAB container implementation for Advanced High-Assurance Boot.
This module provides classes for creating, parsing, and manipulating AHAB containers used in NXP’s Advanced High-Assurance Boot architecture. It supports multiple container versions, signature verification, encrypted firmware images, and SRK management for secure boot chains. Main classes include AHABContainerBase, AHABContainer, AHABContainerV1forV2, and AHABContainerV2 for different container versions and configurations.
- class spsdk.image.ahab.ahab_container.AHABContainerBase(chip_config, flags=0, fuse_version=0, sw_version=0, signature_block=None)#
Bases:
HeaderContainerAHAB Container base class for secure boot operations.
This class provides the foundation for all AHAB (Advanced High Assurance Boot) container implementations, handling common header format, signature verification, and security configuration. AHAB containers are used for both signed messages and bootable images in NXP secure boot process. Container header structure:
+---------------+----------------+----------------+----------------+ | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +---------------+----------------+----------------+----------------+ | Tag | Length | Version | +---------------+---------------------------------+----------------+ | Flags | +---------------+----------------+---------------------------------+ | # of images | Fuse version | SW version | +---------------+----------------+---------------------------------+ | Reserved | Signature Block Offset | +--------------------------------+---------------------------------+ | Payload (Signed Message or Image Array) | +------------------------------------------------------------------+ | Signature block | +------------------------------------------------------------------+
- Variables:
SIGNATURE_BLOCK – Default signature block class for containers.
TAG – Container tag identifier (must be overridden by subclasses).
VERSION – Container format version.
CONTAINER_SIZE – Default container size in bytes.
Initialize AHAB container with configuration and security parameters.
- Parameters:
chip_config (
AhabChipConfig) – Chip-specific configuration for AHAB container.flags (
int) – Container flags controlling behavior and security settings.fuse_version (
int) – Minimum fuse version required, must be equal to or greater than the version stored in fuses to allow loading this container.sw_version (
int) – Software version used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version.signature_block (
Union[SignatureBlock,SignatureBlockV2,None]) – Optional signature block for container authentication.
- SIGNATURE_BLOCK#
alias of
SignatureBlock
-
TAG:
Union[int,list[int]] = 0#
-
VERSION:
Union[int,list[int]] = 0#
- NAME = 'Container'#
- CONTAINER_SIZE = 1024#
- FLAGS_SRK_SET_OFFSET = 0#
- FLAGS_SRK_SET_SIZE = 2#
- FLAGS_USED_SRK_ID_OFFSET = 4#
- FLAGS_USED_SRK_ID_SIZE = 2#
- FLAGS_SRK_REVOKE_MASK_OFFSET = 8#
- FLAGS_SRK_REVOKE_MASK_SIZE = 4#
-
DIFF_ATTRIBUTES_VALUES:
list[str] = ['flags', 'fuse_version', 'sw_version']#
-
DIFF_ATTRIBUTES_OBJECTS:
list[str] = ['signature_block']#
- set_flags(srk_set='none', used_srk_id=0, srk_revoke_mask=0)#
Set the flags value for AHAB container.
Updates the container flags based on SRK configuration and also synchronizes the chip configuration with the provided values.
- Parameters:
srk_set (
str) – Super Root Key (SRK) set identifierused_srk_id (
int) – Index of the key from SRK set being usedsrk_revoke_mask (
int) – Bitmask indicating which SRK keys are revoked
- Return type:
None
- property flag_srk_set: FlagsSrkSet#
Get SRK set flag in string representation.
Extract and return the SRK (Super Root Key) set flag from the container flags field. The flag indicates which SRK set is being used for authentication.
- Returns:
SRK Set flag enumeration value.
- property flag_used_srk_id: int#
Get the used SRK ID flag from container flags.
This method extracts the SRK (Super Root Key) ID that is currently being used from the container flags field using bit manipulation.
- Returns:
Index of the used SRK ID extracted from flags.
- property flag_srk_revoke_keys: int#
Get SRK revoke mask flag from container flags.
Extracts the SRK (Super Root Key) revoke mask from the container flags field by applying bit shifting and masking operations.
- Returns:
SRK revoke mask value indicating which keys are revoked.
- property flag_srk_revoke_mask: str#
Get SRK revoke mask flag in hexadecimal format.
- Returns:
SRK revoke mask represented as hexadecimal string.
- property srk_count: int#
Get count of used SRK (Super Root Key) signatures in container.
- Returns:
Number of SRK signatures used in the container, 0 if no signature block exists.
- get_srk_hash(srk_id=0)#
Get SRK hash.
Retrieves the SHA256 hash of the Super Root Key (SRK) table for the specified SRK ID. Returns empty bytes if signature block is not available or SRK ID is out of range.
- Parameters:
srk_id (
int) – ID of SRK table in case of using multiple signatures, defaults to 0.- Return type:
bytes- Returns:
SHA256 hash of SRK table, or empty bytes if not available.
- property image_array_len: int#
Get image array length if available.
- Returns:
Length of image array.
- header_length()#
Calculate the total length of AHAB Container header.
The method calculates the base header length and adds the signature block length if present.
- Return type:
int- Returns:
Total length in bytes of AHAB Container header including signature block.
- classmethod format()#
Get format string for binary representation of the container.
Returns the format string that describes the binary layout including flags, software version, fuse version, number of images, signature block offset, and reserved fields.
- Return type:
str- Returns:
Format string describing the binary structure layout.
- update_fields()#
Updates all volatile information in whole container structure.
This method refreshes the signature block, updates the container header length, and signs the image header to ensure all fields are current and consistent.
- Raises:
SPSDKError – When inconsistent image array length is detected.
- Return type:
None
- get_signature_data()#
Get binary data to be signed from the container.
The container must be properly initialized, so the data are valid for signing, i.e. the offsets, lengths etc. must be set prior invoking this method, otherwise improper data will be signed. The whole container gets serialized first. Afterwards the binary data is sliced so only data for signing gets returned. The signature data length is evaluated based on offsets, namely the signature block offset, the container signature offset and the container signature fixed data length.
- Signature data structure::
Container header
Data
to
Sign
S i g n a t u r e
B l o c k
tag
length
length
version
flags
srk table offset
certificate offset
blob offset
signature offset
SRK Table / SRK Table Array
S i g n a t u r e
tag
length
length
version
Signature data fixed length
Reserved
Signature data
- Return type:
bytes- Returns:
Binary data to be signed, empty bytes if signature block is not available.
- sign_itself()#
Sign the container using its signature block if signing is required.
This method performs self-signing of the container when the SRK (Super Root Key) flag is set to a value other than NONE. It validates that a signature block exists before attempting to sign the container with the signature data.
- Raises:
SPSDKError – When signing is required but signature block is missing.
- Return type:
None
- classmethod pre_parse_verify(data)#
Pre-parse and verify AHAB container structure.
This method performs initial validation of the AHAB container header and signature block without full parsing of the container data.
- Parameters:
data (
bytes) – Binary data containing the AHAB container block to pre-parse.- Return type:
Verifier- Returns:
Verifier object containing validation results of the pre-parsed data.
- load_from_config_generic(config)#
Load container configuration into AHAB image object.
Converts the configuration options into an AHAB image object by setting fuse version, software version, chip configuration parameters, and signature block from the provided configuration.
- Parameters:
config (
Config) – Configuration object containing AHAB container settings.- Return type:
None
- post_export(data_path, cnt_ix=None)#
Post export actions for AHAB container.
- Parameters:
data_path (
str) – Path to store exported data files.cnt_ix (
Optional[int]) – Container index.
- Raises:
SPSDKNotImplementedError – Post export action is not implemented.
- Return type:
list[str]
- class spsdk.image.ahab.ahab_container.AHABContainer(chip_config, flags=0, fuse_version=0, sw_version=0, image_array=None, signature_block=None, container_offset=0)#
Bases:
AHABContainerBaseAHAB Container implementation for secure boot image management.
This class represents an AHAB (Advanced High Assurance Boot) container that manages secure boot images and their associated metadata. It handles container structure, image array entries, signature blocks, and provides functionality for encryption, decryption, and validation of boot images. Container header:
+---------------+----------------+----------------+----------------+ | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +---------------+----------------+----------------+----------------+ | Tag | Length | Version | +---------------+---------------------------------+----------------+ | Flags | +---------------+----------------+---------------------------------+ | # of images | Fuse version | SW version | +---------------+----------------+---------------------------------+ | Reserved | Signature Block Offset | +----+---------------------------+---------------------------------+ | I |image0: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | + m |-------------------------------------------------------------+ | g |image1: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | + . |-------------------------------------------------------------+ | A |... | | r |... | | r | | + a |-------------------------------------------------------------+ | y |imageN: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | +----+-------------------------------------------------------------+ | Signature block | +------------------------------------------------------------------+ | | | | | | +------------------------------------------------------------------+ | Data block_0 | +------------------------------------------------------------------+ | | | | +------------------------------------------------------------------+ | Data block_n | +------------------------------------------------------------------+
- Variables:
START_IMAGE_ADDRESS – Default start address for images (0x2000).
START_IMAGE_ADDRESS_NAND – Start address for NAND flash images (0x1C00).
Initialize AHAB container with configuration and optional components.
- Parameters:
chip_config (
AhabChipConfig) – Chip configuration for AHAB container.flags (
int) – Container flags for AHAB processing.fuse_version (
int) – Minimum fuse version required, must be equal to or greater than the version stored in the fuses to allow loading this container.sw_version (
int) – Software version used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.image_array (
Union[list[ImageArrayEntry],list[ImageArrayEntryV2],None]) – Array of image entries, must be number of images long.signature_block (
Union[SignatureBlock,SignatureBlockV2,None]) – Signature block for container authentication.container_offset (
int) – Offset of the container in memory.
-
TAG:
Union[int,list[int]] = 135#
- IAE_TYPE#
alias of
ImageArrayEntry
- SIGNATURE_BLOCK#
alias of
SignatureBlock
- START_IMAGE_ADDRESS = 8192#
- START_IMAGE_ADDRESS_NAND = 7168#
- FLAGS_GDET_ENABLE_OFFSET = 20#
- FLAGS_GDET_ENABLE_SIZE = 2#
- class FlagsGdetBehavior(tag, label, description=None)#
Bases:
SpsdkEnumSPSDK Glitch Detector behavior flags enumeration.
This enumeration defines the runtime behavior options for the Glitch Detector in AHAB containers, controlling when and how the detector operates during authentication and ELE API operations.
- Disabled = (0, 'disabled', 'Glitch Detector is disabled after the first OEM container has been authenticated (default behavior)')#
- EnabledEleApi = (1, 'enabled_eleapi', 'Automatically enable Glitch Detector during all ELE API calls')#
- Enabled = (2, 'enabled', 'Leave Glitch Detector enabled')#
- property image_array_len: int#
Get image array length.
- Returns:
Length of image array.
- property srk_hash: bytes#
Get SRK hash if available.
- Returns:
SHA256 hash of SRK table.
- header_length()#
Calculate the total length of AHAB Container header.
The header length includes the fixed container header, all image array entries, and the signature block if present.
- Return type:
int- Returns:
Total length in bytes of AHAB Container header.
- update_fields()#
Updates all volatile information in whole container structure.
This method performs a complete update of the container by: 1. Encrypting all flagged images that aren’t already encrypted 2. Updating the signature block fields 3. Updating all image entries in the array 4. Recalculating the container header length
- Raises:
SPSDKError – When inconsistent image array length is detected.
- Return type:
None
- decrypt_data()#
Decrypt all encrypted images in the container.
Iterates through all images in the image array and attempts to decrypt those that are marked as encrypted. Uses the signature block’s blob for decryption and validates the decrypted data against the stored hash. Logs success or failure for each decryption attempt.
- Raises:
SPSDKError – If attempting to decrypt without a signature block or blob.
- Return type:
None
- export()#
Export container header into bytes.
The method creates a properly aligned container header that includes all image array entries and an optional signature block. The container is aligned according to CONTAINER_ALIGNMENT requirements.
- Return type:
bytes- Returns:
Bytes representing the complete container header content including signature block.
- post_export(output_path, cnt_ix=None)#
Post-export processing and optional file writing.
Performs post-export operations including SRK hash generation and fuse script creation. Skips processing for NXP containers, DEVHSM containers, and v2x-1 containers.
- Parameters:
output_path (
str) – Base path for output filescnt_ix (
Optional[int]) – Container index for file naming, optional
- Return type:
list[str]- Returns:
List of generated file paths
- Raises:
SPSDKError – When fuse script generation fails
- verify()#
Verify AHAB container data integrity and authenticity.
Performs comprehensive verification of the container including image array validation, encryption verification, and signature authenticity checks. The verification process validates image count consistency, decrypts and verifies encrypted images when DEK is available, and checks container signatures against the configured SRK set.
- Return type:
Verifier- Returns:
Verifier object containing detailed verification results and status.
- classmethod parse(data, chip_config, offset)#
Parse input binary chunk to the container object.
This method reconstructs an AHAB container from binary data by parsing the container header, signature block, and all image array entries with their associated binary images.
- Parameters:
data (
bytes) – Binary data with Container block to parse.chip_config (
AhabChipConfig) – Ahab image chip configuration.offset (
int) – AHAB container offset in the binary data.
- Return type:
Self- Returns:
Object recreated from the binary data.
- property flag_gdet_runtime_behavior: FlagsGdetBehavior#
Get glitch detector runtime behavior flag as enumeration.
Extracts and decodes the glitch detector enable bits from the container flags to determine the runtime behavior configuration.
- Returns:
Glitch detector behavior enumeration value.
- get_config(data_path='./', index=0)#
Create configuration of the AHAB Image.
Generates a complete configuration dictionary for the AHAB container including all images and runtime behavior settings.
- Parameters:
data_path (
str) – Path to store the data files of configuration.index (
int) – Container index.
- Return type:
Config- Returns:
Configuration dictionary containing container and images configuration.
- classmethod load_from_config(chip_config, config, container_ix)#
Create AHAB container from configuration data.
Converts the configuration dictionary into an AHAB container object with proper chip configuration and image array entries.
- Parameters:
chip_config (
AhabChipConfig) – AHAB chip configuration settings.config (
Config) – Configuration dictionary containing container settings.container_ix (
int) – Index of the container being loaded.
- Return type:
Self- Returns:
Configured AHAB Container object.
- image_info()#
Get AHAB Container binary image information.
Creates a BinaryImage object containing metadata and binary data for the AHAB container, including container size, description with SRK set flag and software version.
- Return type:
- Returns:
Binary image object with AHAB container metadata and exported binary data.
- create_srk_hash_fuses_script()#
Create fuses script for Super Root Keys (SRK) hash.
This method generates a fuse script that can be used to program the SRK hash into the device fuses for secure boot verification.
- Return type:
str- Returns:
Fuse script as text string, or error message if SRK hash fuses are not available for the target chip family.
- classmethod get_container_offset(ix)#
Get container offset by index.
Calculate the byte offset for a container based on its index position. Each container has a fixed size, and containers are placed sequentially.
- Parameters:
ix (
int) – Container index (0-3).- Raises:
SPSDKValueError – Invalid container index (negative or greater than 3).
- Return type:
int- Returns:
Container offset in bytes.
- property start_of_images: int#
Get real start of container images.
Finds the minimum image offset among all images in the container’s image array to determine where the actual image data begins.
- Raises:
ValueError – If the image array is empty.
- Returns:
The smallest image offset value from all container images.
- class spsdk.image.ahab.ahab_container.AHABContainerV1forV2(chip_config, flags=0, fuse_version=0, sw_version=0, image_array=None, signature_block=None, container_offset=0)#
Bases:
AHABContainerAHAB Container Version 1 for V2 Images.
This class represents an AHAB container using version 1 format that is specifically designed for use within AHAB images containing V2 containers, providing compatibility between different container versions.
- Variables:
CONTAINER_SIZE – Fixed size of the container (0x4000 bytes).
TAG – Container header tag for V1 containers in V2 images.
Initialize AHAB container with configuration and optional components.
- Parameters:
chip_config (
AhabChipConfig) – Chip configuration for AHAB container.flags (
int) – Container flags for AHAB processing.fuse_version (
int) – Minimum fuse version required, must be equal to or greater than the version stored in the fuses to allow loading this container.sw_version (
int) – Software version used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.image_array (
Union[list[ImageArrayEntry],list[ImageArrayEntryV2],None]) – Array of image entries, must be number of images long.signature_block (
Union[SignatureBlock,SignatureBlockV2,None]) – Signature block for container authentication.container_offset (
int) – Offset of the container in memory.
- CONTAINER_SIZE = 16384#
-
TAG:
Union[int,list[int]] = 130#
- class spsdk.image.ahab.ahab_container.AHABContainerV2(chip_config, flags=0, fuse_version=0, sw_version=0, image_array=None, signature_block=None, container_offset=0)#
Bases:
AHABContainerAHAB Container Version 2 implementation for secure boot image management.
This class implements the Advanced High Assurance Boot (AHAB) container format version 2, providing secure boot capabilities for NXP MCUs. It manages container structure, image array entries, signature blocks, and cryptographic operations for authenticated boot sequences. Container header:
+---------------+----------------+----------------+----------------+ | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +---------------+----------------+----------------+----------------+ | Tag | Length | Version | +---------------+---------------------------------+----------------+ | Flags | +---------------+----------------+---------------------------------+ | # of images | Fuse version | SW version | +---------------+----------------+---------------------------------+ | Reserved | Signature Block Offset | +----+---------------------------+---------------------------------+ | I |image0: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | + m |-------------------------------------------------------------+ | g |image1: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | + . |-------------------------------------------------------------+ | A |... | | r |... | | r | | + a |-------------------------------------------------------------+ | y |imageN: Offset, Size, LoadAddr, EntryPoint, Flags, Hash, IV | +----+-------------------------------------------------------------+ | Signature block | +------------------------------------------------------------------+ | | | | | | +------------------------------------------------------------------+ | Data block_0 | +------------------------------------------------------------------+ | | | | +------------------------------------------------------------------+ | Data block_n | +------------------------------------------------------------------+
- Variables:
VERSION – Container format version identifier (0x02).
CONTAINER_SIZE – Standard container size in bytes (0x4000).
START_IMAGE_ADDRESS – Default start address for images (0xC000).
START_IMAGE_ADDRESS_NAND – Start address for NAND flash images (0xBC00).
Initialize AHAB container with configuration and optional components.
- Parameters:
chip_config (
AhabChipConfig) – Chip configuration for AHAB container.flags (
int) – Container flags for AHAB processing.fuse_version (
int) – Minimum fuse version required, must be equal to or greater than the version stored in the fuses to allow loading this container.sw_version (
int) – Software version used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version field.image_array (
Union[list[ImageArrayEntry],list[ImageArrayEntryV2],None]) – Array of image entries, must be number of images long.signature_block (
Union[SignatureBlock,SignatureBlockV2,None]) – Signature block for container authentication.container_offset (
int) – Offset of the container in memory.
- IAE_TYPE#
alias of
ImageArrayEntryV2
- SIGNATURE_BLOCK#
alias of
SignatureBlockV2
- CONTAINER_SIZE = 16384#
-
VERSION:
Union[int,list[int]] = 2#
- START_IMAGE_ADDRESS = 49152#
- START_IMAGE_ADDRESS_NAND = 48128#
- FLAGS_CHECK_ALL_SIGNATURES_OFFSET = 15#
- FLAGS_CHECK_ALL_SIGNATURES_SIZE = 1#
- FLAGS_FAST_BOOT_OFFSET = 16#
- FLAGS_FAST_BOOT_SIZE = 3#
- class FlagsCheckAllSignatures(tag, label, description=None)#
Bases:
SpsdkEnumAHAB container signature verification flags enumeration.
This enumeration defines the available flags for controlling signature verification behavior in AHAB (Advanced High Assurance Boot) containers, allowing configuration of whether all signatures must be verified or default fuse policy should be applied.
- Default = (0, 'default', 'Apply default fuse policy')#
- CheckAllSignatures = (1, 'check_all_signatures', 'Force verification of all present signatures')#
- property flag_check_all_signatures: FlagsCheckAllSignatures#
Get check all signatures flag as enumeration.
Extracts and returns the check all signatures flag from the container flags by applying bit masking and offset operations.
- Returns:
Check all signatures flag as FlagsCheckAllSignatures enumeration.
- class FlagsFastBoot(tag, label, description=None)#
Bases:
SpsdkEnumFast Boot configuration flags enumeration.
This enumeration defines the available flags for configuring Fast Boot behavior in AHAB containers, controlling hash operations, copy operations, and external accelerator usage for authentication.
- Disabled = (0, 'disabled', 'Fast Boot is disabled')#
- HashAndCopy = (1, 'hash_and_copy', 'ELE will do the hash and copy (when disabled, BootROM will do the copy)')#
- ExternalAccelerator = (2, 'external_accelerator', 'Use external accelerator for authentication (e.g. V2X on i.MX95B0, i.MX943 and i.MX952)')#
- HashAndCopyWithExternalAccelerator = (3, 'hash_and_copy_with_external_accelerator', 'ELE will do hash and copy, and use external accelerator for authentication')#
- property flag_fast_boot: FlagsFastBoot#
Get Fast Boot flags as enumeration.
Extracts and returns the Fast Boot flags from the container flags field by applying bit masking and offset operations.
- Returns:
Fast Boot flags as FlagsFastBoot enumeration value.
- create_srk_hash_fuses_script()#
Create fuses script for Super Root Key (SRK) hash.
Generates a script containing fuse programming commands for the SRK hash values. The script is created for each SRK table in the signature block’s SRK assets. If SRK hash fuses are not available for the target chip family, an error message is returned instead.
- Return type:
str- Returns:
Fuse programming script as text, or error message if fuses not available.
- post_export(output_path, cnt_ix=None)#
Post-export processing and optional file writing.
Generates SRK hash files and fuse scripts for AHAB containers. Skips processing for NXP containers and v2x-1 containers. Creates hash files and corresponding fuse scripts for each SRK table in the signature block.
- Parameters:
output_path (
str) – Base path for output filescnt_ix (
Optional[int]) – Container index for file naming, optional
- Return type:
list[str]- Returns:
List of generated file paths including hash files and fuse scripts
- property srk_hash0: bytes#
Get SRK hash if available.
- Returns:
SHA256 hash of SRK table.
- property srk_hash1: bytes#
Get SRK hash from index 1 if available.
The method retrieves the SHA256 hash of the Super Root Key (SRK) table from index 1.
- Returns:
SHA256 hash of SRK table from index 1.
AHAB Utilities#
AHAB utility functions for image processing and management.
This module provides utility functions for working with AHAB (Advanced High Assurance Boot) images, including image detection, key blob updates, signing operations, and signature block management.
- spsdk.image.ahab.utils.find_ahab_image_in_file(file_path, image_id=0, start_offset=0)#
Find offset of AHAB image in file by image ID.
The method searches through the file starting from the specified offset, reading data in chunks to locate AHAB images and returns the offset of the image with the matching ID.
- Parameters:
file_path (
str) – File path of file containing AHAB image.image_id (
int) – The AHAB image ID to search for, defaults to 0.start_offset (
int) – Start offset in bytes to begin the search from.
- Return type:
int- Returns:
Offset of AHAB image by ID, otherwise value under zero if not found.
- spsdk.image.ahab.utils.ahab_update_keyblob(family, binary, keyblob, container_id, image_id=0, mem_type=None)#
Update keyblob in AHAB image.
This function locates an AHAB container within a binary image and replaces its existing keyblob with a new one. The operation validates both the old and new keyblobs and ensures they have matching sizes before performing the update.
- Parameters:
family (
FamilyRevision) – MCU family revision informationbinary (
str) – Path to AHAB image binary filekeyblob (
str) – Path to new keyblob file to be insertedcontainer_id (
int) – Index of the container to be updatedimage_id (
int) – Index of AHAB image in binary to look for, defaults to 0mem_type (
Optional[str]) – Memory type used for bootable image, optional
- Raises:
SPSDKError – In case the container id is not present
SPSDKError – In case the AHAB image does not contain blob
SPSDKError – In case the length of keyblobs don’t match
SPSDKError – In case AHAB image is not found
- Return type:
None
- spsdk.image.ahab.utils.ahab_re_sign(family, binary, container_id, image_id, sign_provider_0, sign_provider_1=None, mem_type=None)#
Re-sign the AHAB container in AHAB image.
This function locates and updates the signature(s) in an existing AHAB container within a binary image file. It supports both single and dual signature scenarios.
- Parameters:
family (
FamilyRevision) – MCU family revision information.binary (
str) – Path to AHAB image binary file.container_id (
int) – Index of the container to be updated.image_id (
int) – Index of AHAB image in binary to look for.sign_provider_0 (
SignatureProvider) – Signature provider object for main signature.sign_provider_1 (
Optional[SignatureProvider]) – Signature provider object for additional signature.mem_type (
Optional[str]) – Memory type used for bootable image.
- Raises:
SPSDKError – If container ID not present, AHAB image not found, container lacks required signature or SRK table, or dual signing is not supported.
- Return type:
None
- spsdk.image.ahab.utils.ahab_sign_image(image_path, config, mem_type, image_id=0)#
Sign AHAB container set.
Parse segments in Bootable image and sign non-NXP AHAB containers. The method validates the configuration, loads the bootable image, and processes each AHAB segment to sign OEM containers while skipping NXP and V2X containers.
- Parameters:
image_path (
str) – Path to the image file to sign.config (
Config) – Configuration object containing signing parameters and validation schemas.mem_type (
str) – Memory type label for the target device.image_id (
int) – The AHAB Image ID to process, defaults to 0.
- Raises:
SPSDKError – Invalid configuration or image parsing errors.
- Return type:
tuple[bytes,BootableImage]- Returns:
Tuple of signed image data as bytes and bootable image object.
- spsdk.image.ahab.utils.ahab_fix_signature_block_version(family, binary)#
Fix signature block version in AHAB v2 signature blocks.
The imx-mkimage tool is known to create incorrect signature block versions. This method corrects the version to match the expected AHAB v2 signature block version by scanning the binary data for signature blocks with version 0 and updating them to version 1.
- Parameters:
family (
FamilyRevision) – Family revision of the target device.binary (
str) – Path to the binary AHAB image file to fix.
- Raises:
SPSDKError – If the fix is not applicable for AHAB v2 containers or if verification of the fixed image fails.
- Return type:
bytes- Returns:
Fixed binary data with corrected signature block versions.
AHAB Container Interface#
AHAB abstract interfaces for secure boot container management.
This module provides abstract base classes and interfaces for AHAB (Advanced High-Assurance Boot) containers used in secure boot implementations. It defines common functionality for container serialization, parsing, validation, and header management across different container types.
- class spsdk.image.ahab.ahab_abstract_interfaces.Container#
Bases:
BaseClassBase class for AHAB container implementations.
Provides common interface for container operations including parsing, exporting, and length calculations. All AHAB container types inherit from this class to ensure consistent behavior across different container formats.
- Variables:
_parser_verifier – Optional verifier for parsing validation.
- classmethod fixed_length()#
Get fixed length of container in bytes.
Fixed length refers to the part of a container that holds fixed values, whereas some entries may have variable length.
- Return type:
int- Returns:
Fixed length in bytes.
- export()#
Export the container to bytes.
- Return type:
bytes- Returns:
Bytes representation of the container.
- Raises:
NotImplementedError – If export is not implemented in derived class.
- classmethod parse(data)#
Parse binary data into a container object.
This method converts raw binary data into a structured container object representation. It serves as the base interface for all AHAB container parsing operations.
- Parameters:
data (
bytes) – Binary input data to parse- Return type:
Self- Returns:
Parsed container object
- Raises:
SPSDKParsingError – If parsing fails
- classmethod format()#
Get container data format for struct operations.
The base implementation returns only endianness (LITTLE_ENDIAN).
- Return type:
str- Returns:
Format string for struct operations.
- class spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainerData(tag, length, version)#
Bases:
objectAHAB container header data holder.
This class represents the fundamental header information found in AHAB (Advanced High Assurance Boot) container headers, providing structured access to tag, length, and version fields with parsing capabilities.
-
tag:
int#
-
length:
int#
-
version:
int#
- classmethod parse(binary, inverted=False)#
Parse binary header into container data structure.
The method unpacks binary data using struct format and handles both normal and inverted field ordering for AHAB header parsing.
- Parameters:
binary (
bytes) – Binary data to parse into header structure.inverted (
bool) – Whether the header fields are in inverted order, defaults to False.
- Return type:
Self- Returns:
Parsed header container data instance.
- Raises:
SPSDKParsingError – If header length is insufficient for parsing.
-
tag:
- class spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainer(tag, length, version)#
Bases:
ContainerAHAB container with header structure containing tag, length and version fields.
This class represents containers used in AHAB (Advanced High Assurance Boot) that include a standardized header format. Most AHAB containers follow this pattern with tag, length and version fields, with exceptions being image arrays and SRK records which have modified header structures.
- Variables:
TAG – Default tag value for the container type.
VERSION – Default version value for the container type.
DIFF_ATTRIBUTES_VALUES – List of value attributes used in diff operations.
DIFF_ATTRIBUTES_OBJECTS – List of object attributes used in diff operations.
Initialize container with header values.
- Parameters:
tag (
int) – Container tag identifier.length (
int) – Container length in bytes.version (
int) – Container version number.
-
TAG:
Union[int,list[int]] = 0#
-
VERSION:
Union[int,list[int]] = 0#
-
DIFF_ATTRIBUTES_VALUES:
list[str] = []#
-
DIFF_ATTRIBUTES_OBJECTS:
list[str] = []#
- classmethod format()#
Format of binary representation.
- Return type:
str- Returns:
Format string for struct operations.
- verify_header()#
Verifies the header of container properties.
Validates tag, length and version against constraints.
- Return type:
Verifier- Returns:
Verifier object with validation results.
- Raises:
SPSDKValueError – If any mandatory field has invalid value.
- verify_parsed_header()#
Verify the parsed header of container properties.
Validates parsed tag, length and version against constraints. If no parsed header is available, adds a warning record to the verification results.
- Return type:
Verifier- Returns:
Verifier object with validation results.
- Raises:
SPSDKValueError – If any mandatory field has invalid value.
- classmethod parse_head(binary)#
Parse binary data to get head members.
Extracts TAG, LENGTH, and VERSION from the first 4 bytes of binary data using the HeaderContainer format for AHAB container processing.
- Parameters:
binary (
bytes) – Binary data to parse (minimum 4 bytes required).- Return type:
tuple[int,int,int]- Returns:
Tuple with TAG, LENGTH, VERSION extracted from header.
- Raises:
SPSDKLengthError – If binary data length is less than 4 bytes.
- classmethod check_container_head(binary, ignore_length=False)#
Validate container header and ensure sufficient data length.
Performs multiple validation steps on the container header: 1. Checks if input data has sufficient length for the fixed header 2. Parses header fields (tag, length, version) 3. Verifies header field values against expected constraints 4. Ensures input data is long enough to contain the entire container
- Parameters:
binary (
bytes) – Input data containing the container headerignore_length (
bool) – Flag to bypass length validation if set to True
- Return type:
Verifier- Returns:
Verification results for all container header checks
- diff(other)#
Get difference of a container with another container.
The method compares this container with another container and returns a dictionary containing all differences found between their attributes and objects.
- Parameters:
other (
object) – Another container to compare against this container.- Return type:
dict[str,dict]- Returns:
Dictionary containing differences between containers with original and new values.
- static print_diff(diff)#
Format and print differences between containers with color coding.
The method formats a dictionary of differences into a human-readable string with color-coded output. Original values are shown in yellow, new values in green, and section headers in cyan. The output is wrapped to fit within specified line limits with proper indentation.
- Parameters:
diff (
dict) – Dictionary containing differences from diff() method- Return type:
str- Returns:
Formatted string representation of differences with color coding
- class spsdk.image.ahab.ahab_abstract_interfaces.HeaderContainerInverted(tag, length, version)#
Bases:
HeaderContainerAHAB container with inverted header field order.
This class extends HeaderContainer to handle binary data where the tag/length/version fields are stored in reverse order compared to the standard header format. It provides specialized parsing for containers that use this inverted field arrangement.
Initialize container with header values.
- Parameters:
tag (
int) – Container tag identifier.length (
int) – Container length in bytes.version (
int) – Container version number.
- classmethod parse_head(binary)#
Parse binary data to get head members from inverted header.
- Parameters:
binary (
bytes) – Binary data to parse for header information.- Raises:
SPSDKLengthError – If binary data length is not enough (less than 4 bytes).
- Return type:
tuple[int,int,int]- Returns:
Tuple with TAG, LENGTH, VERSION extracted from header.
Signed Messages#
AHAB signed message implementation for secure device communication.
This module provides classes and functions to create, parse, and manipulate AHAB (Advanced High Assurance Boot) signed messages. The implementation supports various message types such as key provisioning, lifecycle management, secure fuse operations, and debug authentication. Signed messages are used for secure communication with NXP devices that support EdgeLock security features. The module allows customization of container values according to device-specific requirements.
- class spsdk.image.ahab.signed_msg.Message(family, cert_ver=0, permissions=0, issue_date=None, cmd=0, unique_id=None, unique_id_len=8)#
Bases:
ContainerAHAB signed message container for EdgeLock secure provisioning.
This class represents a signed message used in AHAB (Advanced High Assurance Boot) protocol for communication with EdgeLock-enabled devices. The message consists of a common header containing certificate information, permissions, and unique identifiers, followed by a variable payload section. Message structure:
Off
Byte 3
Byte 2
Byte 1
Byte 0
0x00
Message header
0x10
Message payload
- Message header format:
Off
Byte 3
Byte 2
Byte 1
Byte 0
0x00
Cert version
Permission
Issue date
0x04
Reserved
Command
Reserved
0x08
0x..
Unique ID (64 or 128 bits)
- Variables:
UNIQUE_ID_LEN – Default length of unique identifier in bytes.
TAG – Message tag identifier.
PAYLOAD_LENGTH – Default payload length.
Initialize signed message for EdgeLock device communication.
Creates a message structure that can be signed and sent to devices with EdgeLock security subsystem. The message includes authentication and authorization data required for secure communication.
- Parameters:
family (
FamilyRevision) – Target device family and revision informationcert_ver (
int) – Certificate version number, defaults to 0permissions (
int) – Certificate permissions for future use - must allow the operation requested by the signed message, defaults to 0issue_date (
Optional[int]) – Message issue date as encoded value, defaults to None (current date will be automatically applied)cmd (
int) – Message command identifier, defaults to 0unique_id (
Optional[bytes]) – Device UUID bytes, defaults to None (zero-filled bytes)unique_id_len (
int) – UUID length in bytes - 8 or 16 bytes supported, defaults to 8 bytes
- PAYLOAD_LENGTH = 0#
- TAG = 0#
- UNIQUE_ID_LEN = 8#
- export()#
Export message into bytes array.
Serializes the signed message object into its binary representation by packing the message header fields and appending the unique ID and payload data.
- Return type:
bytes- Returns:
Binary representation of the signed message.
- abstract export_payload()#
Exports message payload to bytes array.
- Return type:
bytes- Returns:
Bytes representation of message payload.
- classmethod format()#
Get format of binary representation without UUID.
Returns the format string that describes the binary layout of the signed message structure, excluding the UUID field. The format includes issue date, permission, certificate version, reserved fields, and command fields.
- Return type:
str- Returns:
Format string describing the binary structure layout.
- abstract get_config()#
Create configuration of the Signed Message.
- Return type:
Config- Returns:
Configuration dictionary.
- classmethod get_message_class(cmd)#
Get the dedicated message class for command.
Searches through all available Message subclasses to find the one that matches the specified command label.
- Parameters:
cmd (
str) – Command label to find the corresponding message class for.- Return type:
Type[Self]- Returns:
Message class that handles the specified command.
- Raises:
SPSDKValueError – When the specified command is not supported.
- classmethod load_from_config(config, family)#
Load message object from configuration data.
The method parses the configuration to extract command information and creates the appropriate message object based on the command type found in the configuration.
- Parameters:
config (
Config) – Message configuration dictionaries containing command definitions.family (
FamilyRevision) – Family revision specification for the target device.
- Raises:
SPSDKError – Invalid configuration when command field doesn’t contain exactly one entry.
- Return type:
Self- Returns:
Message object instance created from the configuration.
- classmethod load_from_config_generic(config)#
Load configuration data into message components.
Converts the general configuration options from container configurations into message object components including certificate version, permissions, issue date, and UUID.
- Parameters:
config (
Config) – Message configuration dictionaries containing cert_version, cert_permission, issue_date, and uuid fields.- Return type:
tuple[int,int,Optional[int],bytes]- Returns:
Tuple containing certificate version, permission, issue date (or None if not specified), and UUID bytes.
- classmethod parse(data, family=None)#
Parse input binary to the signed message object.
The method extracts message components from binary data including issue date, permissions, certificate version, command, and unique ID, then creates the appropriate message class instance based on the command type.
- Parameters:
data (
bytes) – Binary data with Container block to parse.family (
Optional[FamilyRevision]) – Family revision context for parsing.
- Raises:
SPSDKValueError – When family revision is not provided.
- Return type:
Self- Returns:
Object recreated from the binary data.
- abstract parse_payload(data)#
Parse payload from binary data.
This method processes the provided binary data to extract and initialize the payload structure for the signed message.
- Parameters:
data (
bytes) – Binary data containing the payload to be parsed.- Raises:
SPSDKParsingError – Invalid or corrupted payload data format.
- Return type:
None
- property payload_len: int#
Get message payload length in bytes.
- Returns:
Length of the message payload in bytes.
- post_export(output_path)#
Post export operations after the main export process.
This method is called after the primary export functionality to perform any additional operations or cleanup tasks specific to the message type.
- Parameters:
output_path (
str) – Base directory for exported files- Raises:
SPSDKNotImplementedError – If post-export is not implemented for this message type
- Return type:
list[str]
- verify()#
Verify general message properties and return verification results.
Creates a Verifier object to validate the message’s certificate version, permissions, issue date, command type, and unique ID against expected formats and ranges.
- Return type:
Verifier- Returns:
Verifier object containing validation records for all message properties.
- class spsdk.image.ahab.signed_msg.MessageCommands(tag, label, description=None)#
Bases:
SpsdkEnumAHAB signed message commands enumeration.
This enumeration defines the available command types for AHAB (Advanced High Assurance Boot) signed messages, including keystore operations, lifecycle management, and debug authentication.
- DAT_AUTHENTICATION_REQ = (200, 'DAT_AUTHENTICATION_REQ', 'Debug authentication request, internally used for DAT procedure.')#
- KEYSTORE_REPROVISIONING_ENABLE_REQ = (63, 'KEYSTORE_REPROVISIONING_ENABLE_REQ', 'Key store reprovisioning enable')#
- KEY_EXCHANGE_REQ = (71, 'KEY_EXCHANGE_REQ', 'Key exchange signed message content')#
- RETURN_LIFECYCLE_UPDATE_REQ = (160, 'RETURN_LIFECYCLE_UPDATE_REQ', 'Return lifecycle update request.')#
- WRITE_SEC_FUSE_REQ = (145, 'WRITE_SEC_FUSE_REQ', 'Write secure fuse request.')#
- class spsdk.image.ahab.signed_msg.MessageDat(family, cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, challenge_vector=b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', authentication_beacon=0)#
Bases:
MessageDebug authentication request message for AHAB signed messaging.
This class represents a DAT (Debug Authentication Token) message used in the AHAB (Advanced High Assurance Boot) authentication process. It handles the creation, parsing, and validation of debug authentication requests that are sent to devices with EdgeLock security features.
- Variables:
TAG – Message command tag for DAT authentication requests.
PAYLOAD_LENGTH – Fixed payload length in bytes.
CHALLENGE_VECTOR_LEN – Length of the challenge vector in bytes.
Initialize Message for EdgeLock device communication.
Creates a signed message that can be sent to devices with EdgeLock security features. The message includes authentication and challenge-response mechanisms for secure communication.
- Parameters:
family (
FamilyRevision) – Family revision of the devicecert_ver (
int) – Certificate version, defaults to 0permissions (
int) – Certificate permission for future use. The stated permission must allow the operation requested by the signed message, defaults to 0issue_date (
Optional[int]) – Issue date, defaults to None (current date will be applied)unique_id (
Optional[bytes]) – UUID of device, defaults to Noneunique_id_len (
int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes)challenge_vector (
bytes) – 32 bytes of challenge request received from device by DACauthentication_beacon (
int) – Authentication beacon value within range specified by authentication_beacon_length
- Raises:
SPSDKValueError – Invalid authentication beacon length from database
- CHALLENGE_VECTOR_LEN = 32#
- PAYLOAD_LENGTH = 34#
- TAG = 200#
- export_payload()#
Export message payload to bytes array.
The method combines the challenge vector (truncated to the specified length) and the authentication beacon converted to bytes using little-endian byte order.
- Return type:
bytes- Returns:
Bytes representation of message payload containing challenge vector and authentication beacon.
- get_config()#
Create configuration of the Signed Message.
The method generates a configuration dictionary containing the signed message data including challenge vector and authentication beacon values.
- Return type:
Config- Returns:
Configuration dictionary with command data.
- parse_payload(data)#
Parse payload data and extract challenge vector and authentication beacon.
The method extracts the challenge vector from the beginning of the data and parses the authentication beacon from the specified offset using little-endian byte order.
- Parameters:
data (
bytes) – Binary data with payload to parse.- Raises:
IndexError – If data is shorter than expected payload structure.
- Return type:
None
- property payload_len: int#
Get message payload length in bytes.
Calculates the total payload length by adding the base size (32 bytes) to the authentication beacon length.
- Returns:
Total payload length in bytes.
- verify()#
Verify message properties.
Validates the challenge vector length and authentication beacon value range to ensure the signed message meets AHAB specification requirements.
- Return type:
Verifier- Returns:
Verifier object containing validation results and any detected issues.
- class spsdk.image.ahab.signed_msg.MessageKeyExchange(family, cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, key_store_id=0, key_exchange_algorithm=KeyAlgorithm(tag=151126281, label='HKDF SHA256', description='ECDH HKDF SHA256 for key import'), salt_flags=0, derived_key_grp=0, derived_key_size_bits=0, derived_key_type=KeyType(tag=9216, label='AES', description='Possible bit widths: 128/192/256'), derived_key_lifetime=LifeTime(tag=1, label='PERSISTENT', description='Standard persistent key'), derived_key_usage=None, derived_key_permitted_algorithm=KeyDerivationAlgorithm(tag=134217993, label='HKDF SHA256', description='HKDF SHA256 (HMAC two-step)'), derived_key_lifecycle=LifeCycle(tag=1, label='OPEN', description=None), derived_key_id=0, private_key_id=0, input_peer_public_key_digest=b'', input_user_fixed_info_digest=b'', oem_private_key=None, nxp_prod_ka_pub=None)#
Bases:
MessageAHAB key exchange request message for cryptographic key derivation.
This class represents a message used in AHAB (Advanced High Assurance Boot) protocol for requesting cryptographic key exchange operations. It supports ECDH (Elliptic Curve Diffie-Hellman) key exchange and manages the derivation of shared secrets between communicating parties. The message encapsulates all necessary parameters for secure key establishment including key store identifiers, derivation algorithms, and cryptographic material.
- Variables:
TAG – Message command tag identifier for key exchange requests.
PAYLOAD_LENGTH – Fixed payload length in bytes (27 * 4 = 108 bytes).
PAYLOAD_VERSION – Message payload version (0x07).
PAYLOAD_FORMAT – Binary format specification for message serialization.
Initialize key exchange signed message with ECDH support.
Creates a new instance of the key exchange signed message class with support for Elliptic Curve Diffie-Hellman (ECDH) key agreement protocol. This message is used for secure key derivation and exchange operations in NXP MCU security subsystems.
- Parameters:
family (
FamilyRevision) – Family revision for the message.cert_ver (
int) – Certificate version, defaults to 0.permissions (
int) – Certificate permission for future use. The stated permission must allow the operation requested by the signed message, defaults to 0.issue_date (
Optional[int]) – Issue date, defaults to None (current date will be applied).unique_id (
Optional[bytes]) – UUID of device, defaults to None.unique_id_len (
int) – UUID length - 64 or 128 bits, defaults to 64 bits (8 bytes).key_store_id (
int) – Key store ID where to store the derived key. Must be the key store ID related to the key management handle set in the command API, defaults to 0.key_exchange_algorithm (
KeyAlgorithm) – Algorithm used by the key exchange process (HKDF_SHA256 or HKDF_SHA384), defaults to HKDF_SHA256.salt_flags (
int) – Bit field indicating requested operations. Bit 0: Salt in HKDF-extract step (0=zeros salt, 1=peer public key hash). Bit 1: ELE import salt for deriving OEM_IMPORT_WRAP_SK and OEM_IMPORT_CMAC_SK (0=zeros, 1=device SRKH). Bits 2-15 reserved, defaults to 0.derived_key_grp (
int) – Derived key group (0-99). Keys in same group can be managed through Manage key group command, defaults to 0.derived_key_size_bits (
int) – Derived key size in bits, defaults to 0.derived_key_type (
KeyType) – Derived key type (AES, HMAC, or OEM_IMPORT_MK_SK), defaults to AES.derived_key_lifetime (
LifeTime) – Derived key lifetime (VOLATILE, PERSISTENT, or PERMANENT), defaults to PERSISTENT.derived_key_usage (
Optional[list[KeyUsage]]) – List of derived key usage permissions (Cache, Encrypt, Decrypt, Sign message, Verify message, Sign hash, Verify hash, Derive), defaults to None.derived_key_permitted_algorithm (
KeyDerivationAlgorithm) – Derived key permitted algorithm for HKDF operations, defaults to HKDF_SHA256.derived_key_lifecycle (
LifeCycle) – Derived key lifecycle (CURRENT, OPEN, CLOSED, or CLOSED_AND_LOCKED), defaults to OPEN.derived_key_id (
int) – Derived key ID. Use specific ID for persistent/permanent keys or 0 to let FW choose, defaults to 0.private_key_id (
int) – Identifier in ELE key storage of private key for key agreement process, defaults to 0.input_peer_public_key_digest (
bytes) – Input peer public key digest buffer (SHA256), defaults to empty bytes.input_user_fixed_info_digest (
bytes) – Input user fixed info digest buffer (SHA256), defaults to empty bytes.oem_private_key (
Optional[PrivateKeyEcc]) – OEM P256 private key for ECDH, defaults to None.nxp_prod_ka_pub (
Optional[PublicKeyEcc]) – NXP production key agreement public key, defaults to None.
- PAYLOAD_FORMAT = '<BBHLLHHHHLLLLLL32s32s'#
- PAYLOAD_LENGTH = 108#
- PAYLOAD_VERSION = 7#
- TAG = 71#
- export_derived_keys(output_dir='./')#
Export derived keys to files.
The method exports all derived cryptographic keys (shared secret, OEM import keys) to binary files in the specified output directory. Creates the directory if it doesn’t exist.
- Parameters:
output_dir (
str) – Directory path to save the key files, defaults to current directory.- Raises:
SPSDKError – If ECDH has not been performed or output directory is invalid.
- Return type:
list[str]- Returns:
List of file paths where the keys were exported.
- export_payload()#
Export message payload to bytes array.
Converts the signed message object into its binary representation by packing all the message fields according to the PAYLOAD_FORMAT structure.
- Return type:
bytes- Returns:
Bytes representation of message payload.
- get_config()#
Create configuration of the Signed Message.
Generates a configuration dictionary containing all key exchange parameters and command settings for the signed message, including key store information, algorithm settings, derived key properties, and input digests.
- Return type:
Config- Returns:
Configuration dictionary with command and key exchange settings.
- get_derived_keys_info()#
Get information about derived keys for external use.
This method provides access to the derived cryptographic keys in hexadecimal string format for debugging, logging, or external processing purposes.
- Return type:
dict[str,Optional[str]]- Returns:
Dictionary with key names as keys and hex string representations of derived keys as values. Keys include ‘shared_secret’, ‘oem_import_mk_sk’, ‘oem_import_wrap_sk’, and ‘oem_import_cmac_sk’. Values are None if the corresponding key is not available.
- property oem_import_cmac_sk: bytes | None#
Get the derived OEM Import CMAC secret key.
- Returns:
The derived OEM Import CMAC secret key if available, None otherwise.
- property oem_import_mk_sk: bytes | None#
Get the derived OEM_Import_MK_SK.
- Returns:
The derived OEM Import Master Key Signing Key bytes, or None if not set.
- property oem_import_wrap_sk: bytes | None#
Get the derived OEM Import Wrap Secret Key.
This method retrieves the OEM Import Wrap Secret Key that has been derived during the signed message processing. The key is used for wrapping operations in OEM import scenarios.
- Returns:
The derived OEM Import Wrap Secret Key as bytes, or None if not available.
- parse_payload(data)#
Parse payload from binary data.
Unpacks binary payload data and converts raw values to appropriate enum types for key exchange algorithm, derived key properties, and usage flags.
- Parameters:
data (
bytes) – Binary data with payload to parse.- Return type:
None
- perform_ecdh_key_derivation(srkh=None)#
Perform ECDH key derivation following the C code flow.
This method performs a multi-step key derivation process: 1. Performs ECDH with NXP_PROD_KA_PUB to get shared secret 2. Derives OEM_Import_MK_SK from shared secret using HKDF 3. Derives OEM_Import_Wrap_SK and OEM_Import_CMAC_SK from OEM_Import_MK_SK The salt used in derivation steps 2 and 3 depends on salt_flags configuration and availability of SRKH parameter.
- Parameters:
srkh (
Optional[bytes]) – Optional SRKH bytes for salt in key derivation, defaults to None- Raises:
SPSDKError – If ECDH keys are not provided or ECDH fails
- Return type:
None
- post_export(output_path)#
Export remaining derived keys to files.
This method handles the post-export process by delegating to the export_derived_keys method to write any remaining cryptographic keys to the filesystem.
- Parameters:
output_path (
str) – Base directory path where the derived key files will be exported.- Return type:
list[str]- Returns:
List of file paths where the derived keys were successfully exported.
Get the ECDH shared secret.
- Returns:
The ECDH shared secret bytes if available, None otherwise.
- verify()#
Verify message properties and validate all key derivation parameters.
Performs comprehensive verification of the signed message including key store ID, key exchange algorithm, salt flags, derived key properties, and ECDH-related components. Validates byte lengths for digests and derived keys when available.
- Return type:
Verifier- Returns:
Verifier object containing validation results for all message components.
- class spsdk.image.ahab.signed_msg.MessageKeyStoreReprovisioningEnable(family, cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, monotonic_counter=0, user_sab_id=0)#
Bases:
MessageAHAB key store reprovisioning enable request message.
This class represents a signed message used to enable key store reprovisioning operations in AHAB (Advanced High Assurance Boot) security subsystem. It handles the creation and management of reprovisioning enable requests with proper authentication and validation.
- Variables:
TAG – Message command tag identifier.
PAYLOAD_LENGTH – Fixed payload length in bytes.
PAYLOAD_FORMAT – Binary format specification for payload structure.
FLAGS – HSM storage flags configuration.
TARGET – Target ELE (EdgeLock Enclave) identifier.
Initialize key store reprovisioning enable signed message.
Creates a signed message for enabling key store reprovisioning operations with specified security parameters and device identification.
- Parameters:
family (
FamilyRevision) – Family revision for target devicecert_ver (
int) – Certificate version, defaults to 0permissions (
int) – Certificate permissions for future use, must allow the operation requested by the signed message, defaults to 0issue_date (
Optional[int]) – Issue date timestamp, defaults to None (current date applied)unique_id (
Optional[bytes]) – UUID of target device, defaults to Noneunique_id_len (
int) – UUID length in bytes (8 or 16), defaults to 8 bytesmonotonic_counter (
int) – Monotonic counter value, defaults to 0user_sab_id (
int) – User SAB identifier, defaults to 0
- FLAGS = 0#
- PAYLOAD_FORMAT = '<BBHLL'#
- PAYLOAD_LENGTH = 12#
- TAG = 63#
- TARGET = 0#
- export_payload()#
Export message payload to bytes array.
The method packs the message payload fields (flags, target, reserved, monotonic_counter, user_sab_id) into a binary format using the predefined PAYLOAD_FORMAT structure.
- Return type:
bytes- Returns:
Bytes representation of message payload.
- get_config()#
Create configuration of the Signed Message.
The method generates a configuration dictionary containing general settings and command-specific parameters including monotonic counter and user SAB ID values formatted as hexadecimal strings.
- Return type:
Config- Returns:
Configuration dictionary with signed message settings.
- parse_payload(data)#
Parse payload from binary data.
Extracts and assigns payload fields including flags, target, reserved field, monotonic counter, and user SAB ID from the provided binary data.
- Parameters:
data (
bytes) – Binary data containing the payload to parse.- Raises:
struct.error – If data is too short or has invalid format.
- Return type:
None
- verify()#
Verify message properties.
Performs verification of the signed message by checking flags, target, reserved fields, monotonic counter, and user SAB ID against expected values.
- Return type:
Verifier- Returns:
Verifier object containing verification results for all message properties.
- class spsdk.image.ahab.signed_msg.MessageReturnLifeCycle(family, cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, life_cycle=0)#
Bases:
MessageAHAB signed message for device life cycle management.
This class represents a signed message used to request life cycle changes on devices with EdgeLock security subsystem. It handles the creation, serialization, and configuration of life cycle update requests.
- Variables:
TAG – Message command tag identifier.
PAYLOAD_LENGTH – Fixed payload length in bytes.
Initialize AHAB signed message for EdgeLock device communication.
Creates a message structure that can be signed and sent to devices with EdgeLock security subsystem for life cycle management operations.
- Parameters:
family (
FamilyRevision) – Family revision of the target device.cert_ver (
int) – Certificate version, defaults to 0.permissions (
int) – Certificate permissions for future use. Must allow the operation requested by the signed message, defaults to 0.issue_date (
Optional[int]) – Message issue date. If None, current date will be used.unique_id (
Optional[bytes]) – Unique identifier of the target device, defaults to None.unique_id_len (
int) – Length of unique ID in bytes (8 or 16), defaults to 8 bytes.life_cycle (
int) – Target life cycle state to request, defaults to 0.
- PAYLOAD_LENGTH = 4#
- TAG = 160#
- export_payload()#
Export message payload to bytes array.
The method converts the life cycle value to a 4-byte little-endian byte representation that forms the message payload.
- Return type:
bytes- Returns:
Bytes representation of message payload containing life cycle data.
- get_config()#
Create configuration of the Signed Message.
Generates a configuration dictionary containing the general configuration settings and command-specific parameters including the life cycle value.
- Return type:
Config- Returns:
Configuration dictionary with general settings and command parameters.
- parse_payload(data)#
Parse payload data and extract lifecycle information.
The method extracts the lifecycle value from the first 4 bytes of the provided binary data using little-endian byte order.
- Parameters:
data (
bytes) – Binary data with payload to parse.- Return type:
None
- verify()#
Verify message properties and life cycle information.
This method extends the parent verification by adding a life cycle record to the verification results.
- Return type:
Verifier- Returns:
Verifier object containing verification results with life cycle data.
- class spsdk.image.ahab.signed_msg.MessageV2(family, cert_ver=0, permissions=0, issue_date=None, cmd=0, unique_id=None, unique_id_len=8)#
Bases:
MessageAHAB Signed Message Version 2.
This class represents a version 2 signed message in the AHAB (Advanced High Assurance Boot) format, extending the base Message class with version-specific functionality and structure.
- Variables:
UNIQUE_ID_LEN – Length of the unique identifier field in bytes.
Initialize signed message for EdgeLock device communication.
Creates a message structure that can be signed and sent to devices with EdgeLock security subsystem. The message includes authentication and authorization data required for secure communication.
- Parameters:
family (
FamilyRevision) – Target device family and revision informationcert_ver (
int) – Certificate version number, defaults to 0permissions (
int) – Certificate permissions for future use - must allow the operation requested by the signed message, defaults to 0issue_date (
Optional[int]) – Message issue date as encoded value, defaults to None (current date will be automatically applied)cmd (
int) – Message command identifier, defaults to 0unique_id (
Optional[bytes]) – Device UUID bytes, defaults to None (zero-filled bytes)unique_id_len (
int) – UUID length in bytes - 8 or 16 bytes supported, defaults to 8 bytes
- UNIQUE_ID_LEN = 16#
- class spsdk.image.ahab.signed_msg.MessageWriteSecureFuse(family, cert_ver=0, permissions=0, issue_date=None, unique_id=None, unique_id_len=8, fuse_id=0, length=0, flags=0, data=None)#
Bases:
MessageAHAB secure fuse write request message.
This class represents a signed message used to write secure fuses on devices with EdgeLock security subsystem. It encapsulates the fuse write operation parameters including fuse ID, data, and security flags for authenticated fuse programming.
- Variables:
TAG – Message command tag for write secure fuse requests.
PAYLOAD_FORMAT – Binary format specification for message payload.
Initialize EdgeLock signed message for device communication.
Creates a message structure that can be signed and sent to devices with EdgeLock security subsystem for fuse operations and other secure commands.
- Parameters:
family (
FamilyRevision) – Family revision of the target device.cert_ver (
int) – Certificate version, defaults to 0.permissions (
int) – Certificate permissions for future use, must allow the requested operation, defaults to 0.issue_date (
Optional[int]) – Message issue date, defaults to None (current date will be used).unique_id (
Optional[bytes]) – Device UUID for identification, defaults to None.unique_id_len (
int) – UUID length in bytes (8 for 64-bit, 16 for 128-bit), defaults to 8 bytes.fuse_id (
int) – Target fuse identifier, defaults to 0.length (
int) – Fuse data length, defaults to 0.flags (
int) – Fuse operation flags, defaults to 0.data (
Optional[list[int]]) – List of fuse values to be written, defaults to None.
- PAYLOAD_FORMAT = '<HBB'#
- TAG = 145#
- export_payload()#
Export message payload to bytes array.
The method packs the fuse ID, length, and flags using the payload format, then appends each fuse data element as 4-byte little-endian values.
- Return type:
bytes- Returns:
Bytes representation of message payload.
- get_config()#
Create configuration of the Signed Message.
Generates a configuration dictionary containing the signed message structure with fuse writing command, including fuse ID, flags, and data formatted as hexadecimal strings.
- Return type:
Config- Returns:
Configuration dictionary with command structure for signed message.
- parse_payload(data)#
Parse payload data and populate fuse information.
The method extracts fuse ID, length, and flags from the binary data header, then parses the fuse data values according to the specified length.
- Parameters:
data (
bytes) – Binary data with payload to parse.- Raises:
struct.error – If data format is invalid or insufficient data provided.
- Return type:
None
- property payload_len: int#
Get message payload length in bytes.
Calculates the total payload length including the base 4 bytes plus 4 bytes for each fuse data entry.
- Returns:
Total payload length in bytes.
- verify()#
Verify message properties and fuse data integrity.
Performs comprehensive verification of the signed message including validation of fuse data existence, count consistency, and individual fuse data values. Each verification step is recorded with appropriate result status.
- Return type:
Verifier- Returns:
Verifier object containing all verification results and status records.
- class spsdk.image.ahab.signed_msg.SignedMessage(family, signed_msg_container=None)#
Bases:
FeatureBaseClassAHAB Signed Message handler for secure boot operations.
This class manages AHAB (Advanced High Assurance Boot) signed messages used in NXP MCU secure boot process. It handles signed message containers, validates configurations, and provides export functionality for bootable images.
- Variables:
FEATURE – Database feature identifier for AHAB operations.
Initialize AHAB Image instance.
Creates a new AHAB Image with the specified device family and optional signed message container. Initializes chip configuration, database connection, and container type tracking.
- Parameters:
family (
FamilyRevision) – Device family revision specification.signed_msg_container (
Union[SignedMessageContainer,SignedMessageContainerV2,None]) – Optional signed message container (V1 or V2), defaults to None.
- Raises:
SPSDKValueError – Invalid input configuration.
-
FEATURE:
str= 'ahab'#
- property container_type: Type[SignedMessageContainer] | Type[SignedMessageContainerV2]#
Get container class type.
Determines and returns the type of the signed message container. The container type is cached after first determination to avoid repeated type checking.
- Raises:
SPSDKError – When signed message container is None and type cannot be determined.
- Returns:
Class type of the signed message container (either SignedMessageContainer or SignedMessageContainerV2).
- export()#
Export Signed message image.
The method validates the signed message and exports the complete image data including all necessary components for deployment.
- Raises:
SPSDKError – If validation of the signed message fails.
- Return type:
bytes- Returns:
Complete signed message image as bytes.
- property family: FamilyRevision#
Get the family revision information.
- Returns:
Family revision configuration for the current chip.
- get_config(data_path='./')#
Create configuration of the Signed Message.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary.
- classmethod get_config_template(family, message=None)#
Get AHAB configuration template.
The method generates a configuration template for AHAB signed messages. If a specific message type is provided, the template will be filtered to include only that message type, otherwise all available message types for the family will be included.
- Parameters:
family (
FamilyRevision) – Family for which the template should be generated.message (
Optional[MessageCommands]) – Generate the template just for one message type, if not used, it’s generated for all messages.
- Return type:
str- Returns:
Configuration template string for the specified family and message type.
- get_srk_hash(srk_id=0)#
Get SRK hash.
Retrieves the SHA256 hash of the Super Root Key (SRK) table from the signed message container.
- Parameters:
srk_id (
int) – ID of SRK table in case of using multiple signatures, defaults to 0- Return type:
bytes- Returns:
SHA256 hash of SRK table, or empty bytes if no signed message container exists
- classmethod get_validation_schemas(family)#
Get list of validation schemas for the specified family.
This method retrieves validation schemas by delegating to the appropriate signed message class based on the provided family revision.
- Parameters:
family (
FamilyRevision) – Family revision for which the validation schemas should be generated.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries.
- classmethod get_validation_schemas_from_cfg(config)#
Get validation schemas based on configuration.
This method validates the basic configuration, extracts family information, determines the appropriate signed message class, and returns the validation schemas specific to that family.
- Parameters:
config (
Config) – Valid configuration object containing family and other settings- Raises:
SPSDKError – Invalid configuration or unsupported family
- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the signed message class
- image_info()#
Get Image info object for the signed message.
Creates a BinaryImage representation of the signed message with metadata including size, alignment, and description. If a signed message container exists, its image info is added as a sub-image.
- Return type:
- Returns:
Binary image object containing signed message information.
- classmethod load_from_config(config)#
Create signed message object from configuration data.
Loads family revision information and creates appropriate signed message container based on the chip configuration.
- Parameters:
config (
Config) – Configuration dictionary containing signed message settings.- Return type:
Self- Returns:
Configured signed message object.
- classmethod parse(data, family=None)#
Parse input binary chunk to the container object.
The method parses binary data containing a signed message and creates the appropriate signed message container based on the detected message type.
- Parameters:
data (
bytes) – Input binary data to parse.family (
Optional[FamilyRevision]) – The MCU family revision used for parsing configuration.
- Raises:
SPSDKValueError – Missing family parameter.
- Return type:
Self- Returns:
Parsed signed message container object.
- post_export(output_path)#
Export post-processing artifacts after signed message generation.
This method delegates the post-export functionality to the underlying signed message container’s message component, which handles the creation and organization of artifacts generated during the export process.
- Parameters:
output_path (
str) – Directory path where post-export artifacts will be saved.- Return type:
list[str]- Returns:
List of file paths to the generated post-export artifacts.
- classmethod pre_parse_verify(data)#
Pre-parse verify of AHAB container.
Performs initial verification of the AHAB container by determining its type and delegating to the appropriate type-specific pre-parse verification method.
- Parameters:
data (
bytes) – Binary data with Container block to pre-parse.- Return type:
Verifier- Returns:
Verifier object containing pre-parsed binary data verification results.
- property srk_count: int#
Get count of used SRKs.
- Returns:
Number of Super Root Keys (SRKs) used in the signed message container, or 0 if no container exists.
- update_fields()#
Update all volatile fields in every Signed message container.
This method automatically refreshes dynamic fields that may change during the container’s lifecycle, ensuring data consistency and proper validation.
- Return type:
None
- verify()#
Verify the signed message image integrity and structure.
Creates a verification report that checks the presence and validity of the signed message container within this signed message image.
- Return type:
Verifier- Returns:
Verifier object containing the verification results and any child verifications.
- class spsdk.image.ahab.signed_msg.SignedMessageContainer(chip_config, flags=0, fuse_version=0, sw_version=0, message=None, signature_block=None, encrypt_iv=None)#
Bases:
AHABContainerBaseAHAB Signed Message Container for secure message processing.
This class represents a signed message container in the AHAB (Advanced High Assurance Boot) format, managing cryptographically signed messages with optional encryption. It handles the complete container structure including message descriptors, headers, payloads, and signature blocks for secure boot and messaging operations. DAT Container:
+-----+--------------+--------------+----------------+----------------+ |Off | Byte 3 | Byte 2 | Byte 1 | Byte 0 | +-----+--------------+--------------+----------------+----------------+ |0x00 | Tag | Length (MSB) | Length (LSB) | Version | +-----+--------------+--------------+----------------+----------------+ |0x04 | Flags | +-----+--------------+--------------+---------------------------------+ |0x08 | Reserved | Fuse version | Software version | +-----+--------------+--------------+---------------------------------+ |0x10 | Signature Block | +-----+---------------------------------------------------------------+
- Signed Message::
Off
Byte 3
Byte 2
Byte 1
Byte 0
0x00
Tag
Length (MSB)
Length (LSB)
Version
0x04
Flags
0x08
Reserved
Fuse version
Software version
0x10
Message descriptor
0x34
Message header
0x44
Message payload
0xXX
Signature Block
- Message descriptor::
Off
Byte 3
Byte 2
Byte 1
Byte 0
0x00
Reserved
Flags
0x04
IV (256 bits)
- Variables:
TAG – Container tag identifier for signed messages.
ENCRYPT_IV_LEN – Length of encryption initialization vector (32 bytes).
Initialize AHAB signed message container.
Creates a signed message container for AHAB (Advanced High Assurance Boot) with optional encryption support and signature verification.
- Parameters:
chip_config (
AhabChipConfig) – Chip configuration for AHAB operations.flags (
int) – Container flags for message processing.fuse_version (
int) – Minimum fuse version required, must be equal to or greater than the version stored in fuses to allow loading this container.sw_version (
int) – Software version used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version.message (
Union[Message,MessageV2,None]) – Message command to be signed, can be Message or MessageV2.signature_block (
Union[SignatureBlock,SignatureBlockV2,None]) – Signature block for message verification, can be SignatureBlock or SignatureBlockV2.encrypt_iv (
Optional[bytes]) – Encryption Initial Vector, when provided enables encryption.
- ENCRYPT_IV_LEN = 32#
- NAME = 'Signed Message'#
- SIGNATURE_BLOCK#
alias of
SignatureBlock
- TAG: Union[int, list[int]] = 137#
- export()#
Export the signed image into one chunk.
- Raises:
SPSDKValueError – If the number of images doesn’t correspond to the number of entries in image array info.
- Return type:
bytes- Returns:
Images exported into single binary.
- classmethod format()#
Get binary format string for signed message structure.
Returns the format string used for struct packing/unpacking of the signed message binary representation, including descriptor flags, reserved fields, and initialization vector.
- Return type:
str- Returns:
Format string for struct operations with binary data.
- get_config(data_path='./')#
Create configuration of the Signed Message.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary.
- classmethod get_validation_schemas(family)#
Get list of validation schemas for signed message.
The method retrieves and configures validation schemas specific to the given family, including both general family schema and signed message schema.
- Parameters:
family (
FamilyRevision) – Family revision for which the validation schema should be generated.- Return type:
list[dict[str,Any]]- Returns:
List containing family schema and signed message schema dictionaries.
- image_info()#
Get Image info object for the signed message.
Creates a BinaryImage representation of the signed message containing metadata and binary data for further processing or analysis.
- Return type:
- Returns:
BinaryImage object containing signed message information and binary data.
- classmethod load_from_config(chip_config, config)#
Load signed message object from configuration.
Creates a new signed message instance using the provided chip configuration and populates it with data from the configuration dictionary.
- Parameters:
chip_config (
AhabChipConfig) – AHAB chip configuration containing chip-specific settings.config (
Config) – Configuration dictionary containing signed message parameters.
- Return type:
Self- Returns:
Configured signed message object.
- classmethod parse(data, chip_config)#
Parse input binary data to create a signed message container object.
This method deserializes binary data containing an AHAB container block into a SignedMessage object, extracting all relevant fields including flags, versions, message content, and signature block.
- Parameters:
data (
bytes) – Binary data containing the AHAB container block to parse.chip_config (
AhabChipConfig) – AHAB chip configuration settings for the target device.
- Return type:
Self- Returns:
Parsed SignedMessage container object with all extracted fields.
- update_fields()#
Updates all volatile information in whole container structure.
This method updates the signature block if present, recalculates the container length, and signs the image header when SRK (Super Root Key) is configured.
- Raises:
SPSDKError – When inconsistent image array length is detected.
- Return type:
None
- verify()#
Verify message properties and structure.
Performs comprehensive verification of the signed message including encryption initialization vector validation and message content verification.
- Return type:
Verifier- Returns:
Verifier object containing verification results and any child verification records.
- class spsdk.image.ahab.signed_msg.SignedMessageContainerV2(chip_config, flags=0, fuse_version=0, sw_version=0, message=None, signature_block=None, encrypt_iv=None)#
Bases:
SignedMessageContainerAHAB Signed Message Container Version 2.
This class implements the version 2 specification of the AHAB (Advanced High Assurance Boot) signed message container format. It extends the base SignedMessageContainer with V2-specific signature blocks, message types, and validation schemas that support enhanced security features including dual signature verification and certificate-based authentication.
- Variables:
VERSION – Container format version identifier (0x02).
SIGNATURE_BLOCK – Type alias for V2 signature block implementation.
MESSAGE_TYPE – Type alias for V2 message format implementation.
Initialize AHAB signed message container.
Creates a signed message container for AHAB (Advanced High Assurance Boot) with optional encryption support and signature verification.
- Parameters:
chip_config (
AhabChipConfig) – Chip configuration for AHAB operations.flags (
int) – Container flags for message processing.fuse_version (
int) – Minimum fuse version required, must be equal to or greater than the version stored in fuses to allow loading this container.sw_version (
int) – Software version used by PHBC (Privileged Host Boot Companion) to select between multiple images with same fuse version.message (
Union[Message,MessageV2,None]) – Message command to be signed, can be Message or MessageV2.signature_block (
Union[SignatureBlock,SignatureBlockV2,None]) – Signature block for message verification, can be SignatureBlock or SignatureBlockV2.encrypt_iv (
Optional[bytes]) – Encryption Initial Vector, when provided enables encryption.
- SIGNATURE_BLOCK#
alias of
SignatureBlockV2
- VERSION: Union[int, list[int]] = 2#
- classmethod get_validation_schemas(family)#
Get list of validation schemas for AHAB signed message.
The method retrieves and customizes validation schemas based on family-specific features like container types, certificate support, and signature validation requirements.
- Parameters:
family (
FamilyRevision) – Family revision for which the validation schema should be generated.- Return type:
list[dict[str,Any]]- Returns:
List containing family schema and customized signed message schema.
- class spsdk.image.ahab.signed_msg.SignedMessageTags(tag, label, description=None)#
Bases:
SpsdkEnumEnumeration of AHAB signed message container tags.
This enumeration defines the standardized tags used to identify and categorize signed message containers in the AHAB (Advanced High Assurance Boot) format.
- Variables:
SIGNED_MSG – Tag identifier for signed message containers.
- SIGNED_MSG = (137, 'SIGNED_MSG', 'Signed message.')#
Type-Length-Value blobs#
SPSDK AHAB TLV (Type-Length-Value) data structure utilities.
This module provides functionality for handling TLV data structures used in AHAB (Advanced High Assurance Boot) context, including TLV parsing, creation, and key import operations.
- class spsdk.image.ahab.tlv.KeyImportTLV(family, key_id=0, permitted_algorithm=KeyAlgorithm(tag=33554441, label='SHA256', description='SHA256 hash algorithm'), key_usage=None, key_type=KeyType(tag=9216, label='AES', description='Possible bit widths: 128/192/256'), key_size_bits=0, key_lifetime=LifeTime(tag=3221356799, label='ELE_KEY_IMPORT_PERMANENT', description='EdgeLock® secure enclave Key import permanent key'), key_lifecycle=LifeCycle(tag=1, label='OPEN', description=None), oem_import_mk_sk_key_id=0, wrapping_algorithm=WrappingAlgorithm(tag=1, label='RFC3394', description='RFC 3394 wrapping'), iv=None, signing_algorithm=KeyImportSigningAlgorithm(tag=1, label='CMAC', description=None), wrapped_private_key=b'', signature=b'')#
Bases:
TLVAHAB Key Import TLV message for secure key provisioning.
This class represents a Type-Length-Value (TLV) structure for importing cryptographic keys into NXP EdgeLock Enclave. It handles key wrapping, signing, and validation according to AHAB (Advanced High Assurance Boot) specifications.
- Variables:
NAME – TLV identifier name for key import operations.
HEADER_MAGIC – Magic string identifier for EdgeLock enclave import format.
Initialize key import blob for secure key provisioning.
Creates a key import blob structure used for importing cryptographic keys into NXP MCU secure elements with specified algorithms, usage permissions, and lifecycle settings.
- Parameters:
family (
FamilyRevision) – Target MCU family revision for compatibilitykey_id (
int) – Key storage identifier in ELE key management system, defaults to 0permitted_algorithm (
KeyAlgorithm) –Cryptographic algorithm for key operations, defaults to SHA256
- Hash Algorithms:
- MD5 0x02000003SHA1 0x02000005SHA224 0x02000008SHA256 0x02000009SHA384 0x0200000ASHA512 0x0200000BSHA3_224 0x02000010SHA3_256 0x02000011SHA3_384 0x02000012SHA3_512 0x02000013SHAKE256 0x02000015
MAC Algorithms: | HMAC SHA256 0x03800009 | HMAC SHA384 0x0380000A | CMAC 0x03C00200
Cipher Algorithms: | ECB NO PADDING 0x04404400 | CBC NO PADDING 0x04404000 | CTR 0x04C01000 | CFB 0x04C01100 | OFB 0x04C01200 | ALL CIPHER 0x84C0FF00
AEAD Algorithms: | CCM 0x05500100 | GCM 0x05500200 | CHACHA20_POLY1305 0x05100500 | ALL AEAD 0x8550FF00
Signature Algorithms: | ECDSA SHA224 0x06000608 | ECDSA SHA256 0x06000609 | ECDSA SHA384 0x0600060A | ECDSA SHA512 0x0600060B | RSA PKCS1 V1.5 SHA224 0x06000208 | RSA PKCS1 V1.5 SHA256 0x06000209 | RSA PKCS1 V1.5 SHA384 0x0600020A | RSA PKCS1 V1.5 SHA512 0x0600020B | RSA PKCS1 V1.5 SHA ANY 0x060002FF | RSA PKCS1 PSS MGF1 SHA224 0x06000308 | RSA PKCS1 PSS MGF1 SHA256 0x06000309 | RSA PKCS1 PSS MGF1 SHA384 0x0600030A | RSA PKCS1 PSS MGF1 SHA512 0x0600030B | RSA PKCS1 PSS MGF1 SHA ANY 0x060003FF | RSA PKCS1 ALL 0x8600FF00 | ED25519PH 0x0600090B | ED448PH 0x06000915 | PURE EDDSA 0x06000800 | ALL EDDSA 0x86000800
Key Exchange Algorithms: | ECDH HKDF SHA256 KEY IMPORT 0x09020109 | ECDH HKDF SHA384 KEY IMPORT 0x0902010A | ECDH HKDF SHA ANY KEY IMPORT 0x090201FF | ECDH HKDF SHA256 0x89020109 | ECDH HKDF SHA384 0x8902010A | ECDH HKDF SHA ANY 0x890201FF
key_usage (
Optional[list[KeyUsage]]) – List of permitted key usage flags (encrypt, decrypt, sign, verify, etc.), | Cache 0x00000004 Permission to cache the key in the ELE internal secure memory. | This usage is set by default by ELE FW for all keys generated or imported. | Encrypt 0x00000100 Permission to encrypt a message with the key. It could be cipher | encryption, AEAD encryption or asymmetric encryption operation. | Decrypt 0x00000200 Permission to decrypt a message with the key. It could be | cipher decryption, AEAD decryption or asymmetric decryption operation. | Sign message 0x00000400 Permission to sign a message with the key. It could be | a MAC generation or an asymmetric message signature operation. | Verify message 0x00000800 Permission to verify a message signature with the key. | It could be a MAC verification or an asymmetric message signature | verification operation. | Sign hash 0x00001000 Permission to sign a hashed message with the key | with an asymmetric signature operation. Setting this permission automatically | sets the Sign Message usage. | Verify hash 0x00002000 Permission to verify a hashed message signature with | the key with an asymmetric signature verification operation. | Setting this permission automatically sets the Verify Message usage. | Derive 0x00004000 Permission to derive other keys from this key. | , defaults to 0 defaults to Nonekey_type (
KeyType) –Type of cryptographic key (AES, HMAC, OEM_IMPORT_MK_SK), defaults to AES
Key type
Value
Key size in bits
AES
0x2400
128/192/256
HMAC
0x1100
224/256/384/512
OEM_IMPORT_MK_SK*
0x9200
128/192/256
key_size_bits (
int) – Key size in bits, defaults to 0key_lifetime (
LifeTime) –Key persistence level (volatile, persistent, permanent), defaults to permanent
ELE_KEY_IMPORT_VOLATILE 0xC0020000 Standard volatile key.ELE_KEY_IMPORT_PERSISTENT 0xC0020001 Standard persistent key.ELE_KEY_IMPORT_PERMANENT 0xC00200FF Standard permanent key., defaults to PERSISTENTkey_lifecycle (
LifeCycle) –Lifecycle stage when key is usable (open, closed, locked), defaults to open
CURRENT 0x00 Key is usable in current lifecycle.OPEN 0x01 Key is usable in open lifecycle.CLOSED 0x02 Key is usable in closed lifecycle.CLOSED and LOCKED 0x04 Key is usable in closed and locked lifecycle.oem_import_mk_sk_key_id (
int) – ELE storage ID of OEM master key for encryption/signing, defaults to 0wrapping_algorithm (
WrappingAlgorithm) –Key blob wrapping method (RFC3394 or AES CBC), defaults to RFC3394
Possible values are: - 0x01: RFC3394 wrapping - 0x02: AES CBC wrapping
iv (
Optional[bytes]) – Initialization vector for CBC wrapping (16 bytes), defaults to Nonesigning_algorithm (
KeyImportSigningAlgorithm) – Algorithm for blob signature verification, defaults to CMACwrapped_private_key (
bytes) – Private key data in encrypted format as defined by the ‘Wrapping Algorithm’. Key used to do the encryption must be OEM_IMPORT_WRAP_SK derived from OEM_IMPORT_MK_SK.signature (
bytes) – Signature of all previous fields of this blob including the signature tag (0x5E) and signature length fields. Key used to do the signature must be OEM_IMPORT_CMAC_SK derived from OEM_IMPORT_MK_SK.
- HEADER_MAGIC = 'edgelockenclaveimport'#
- class Ki(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
X690Type[bytes]Key Import TLV field type for AHAB image processing.
This class represents a TLV (Type-Length-Value) field specifically designed for key import operations in AHAB (Advanced High Assurance Boot) images. It extends the X690 encoding standard to handle key import data structures.
- Variables:
TAG – TLV tag identifier for key import fields.
TYPECLASS – ASN.1 type class specification.
NATURE – List of supported type natures for the field.
- NATURE = [TypeNature.PRIMITIVE]#
The x690 “private/constructed” information
- TAG: int = 0#
The x690 identifier for the type
- TYPECLASS: TypeClass = 'application'#
The x690 type-class (universal, application or context)
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiEncryptedPrk(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record for encrypted private key data.
This class represents a Key Information (Ki) TLV record that contains encrypted private key material for secure key provisioning operations.
- Variables:
TAG – TLV tag identifier for encrypted private key records (0x15).
- TAG: int = 21#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiImportMkSkKeyId(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record for importing Master Key Signing Key identifier.
This class represents a Key Identifier (Ki) TLV record specifically used for importing Master Key Signing Key identifiers in AHAB image processing.
- Variables:
TAG – TLV tag identifier for MK SK KEY import operations.
- TAG: int = 16#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiIv(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record for optional initial vector in AHAB images.
This class represents a Type-Length-Value record that contains an optional initial vector used in AHAB (Advanced High Assurance Boot) image processing. It extends the Ki class to provide specific functionality for initial vector handling.
- Variables:
TAG – TLV tag identifier for initial vector records.
- TAG: int = 18#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiKeyAlgorithm(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record representing key algorithm information.
This class handles the creation and management of Type-Length-Value (TLV) records specifically for key algorithm data in AHAB image format.
- Variables:
TAG – TLV tag identifier for key algorithm records (0x02).
- TAG: int = 2#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiKeyBitsSize(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record for key size information.
This class represents a Type-Length-Value record that stores cryptographic key size data in AHAB image format.
- Variables:
TAG – TLV tag identifier for key size records (0x05).
- TAG: int = 5#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiKeyId(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record representing a Key ID.
This class implements a specific TLV (Type-Length-Value) record type used in AHAB image format for storing key identification information.
- Variables:
TAG – TLV tag identifier for Key ID records (0x01).
- TAG: int = 1#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiKeyLifeCycle(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record for managing key life cycle information.
This class represents a Type-Length-Value (TLV) record that handles key life cycle data in AHAB (Advanced High Assurance Boot) images.
- Variables:
TAG – TLV tag identifier for key life cycle records (0x07).
- TAG: int = 7#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiKeyLifeTime(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record for managing key lifetime information.
This class represents a Type-Length-Value record that handles key lifetime data in AHAB (Advanced High Assurance Boot) image format.
- Variables:
TAG – TLV tag identifier for key lifetime records (0x06).
- TAG: int = 6#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiKeyType(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record representing a key type field.
This class implements a specific TLV (Type-Length-Value) record used in AHAB (Advanced High Assurance Boot) image format to store key type information.
- Variables:
TAG – TLV tag identifier for key type records (0x04).
- TAG: int = 4#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiKeyUsage(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record for key usage information in AHAB images.
This class represents a Type-Length-Value record that specifies key usage constraints and permissions within AHAB (Advanced High Assurance Boot) image structures.
- Variables:
TAG – TLV tag identifier for key usage records (0x03).
- TAG: int = 3#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiMagic(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record representing a magic header in AHAB images.
This class implements a specific type of Key Information (Ki) record that contains magic header data used for AHAB (Advanced High Assurance Boot) image validation and identification.
- Variables:
TAG – TLV tag identifier for magic header records (0x00).
- TAG: int = 0#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiSignature(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiAHAB TLV signature record implementation.
This class represents a signature record in AHAB (Advanced High Assurance Boot) TLV (Type-Length-Value) format, used for cryptographic signature operations in secure boot processes.
- Variables:
TAG – TLV tag identifier for signature records (0x1E).
- TAG: int = 30#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiSigningAlgorithm(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record representing key signing algorithm information.
This class handles the creation and management of Type-Length-Value records specifically for key signing algorithm data in AHAB image format.
- Variables:
TAG – TLV tag identifier for signing algorithm records (0x14).
- TAG: int = 20#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- class KiWrappingAlgorithm(value=<x690.types._SENTINEL_UNINITIALISED object>)#
Bases:
KiTLV record representing key wrapping algorithm configuration.
This class handles the key wrapping algorithm specification within AHAB (Advanced High Assurance Boot) image format, providing the necessary configuration for cryptographic key wrapping operations.
- Variables:
TAG – TLV tag identifier for key wrapping algorithm records.
- TAG: int = 17#
The x690 identifier for the type
- pyvalue: Union[TWrappedPyType, _SENTINEL_UNINITIALISED]#
The decoded (or to-be encoded) Python value
- NAME = 'KEY_IMPORT'#
- export()#
Export key information message payload to bytes array.
The method serializes all key information fields including magic header, key ID, algorithm settings, usage flags, type, size, lifetime, lifecycle, import settings, wrapping configuration, IV (for AES_CBC), signing algorithm, encrypted private key, and signature into a binary format.
- Return type:
bytes- Returns:
Bytes representation of the complete key information message payload.
- get_config(data_path='./')#
Create configuration of the Key Import TLV.
Generates a configuration dictionary containing all the key import parameters including key metadata, wrapping details, and cryptographic signatures.
- Parameters:
data_path (
str) – Path where to store the data files.- Return type:
Config- Returns:
Configuration object with key import TLV settings.
- classmethod parse(data)#
Parse key import data blob from binary data.
Parses TLV-encoded binary data containing key import information and creates a new instance with all the extracted key parameters including algorithms, usage flags, lifecycle settings, and cryptographic material.
- Parameters:
data (
bytes) – Binary data containing TLV-encoded key import data blob.- Raises:
SPSDKParsingError – Invalid magic value in the data blob header.
- Return type:
Self- Returns:
New instance populated with parsed key import parameters.
- property payload_len: int#
Get message payload length in bytes.
- Returns:
Length of the exported message payload in bytes.
- verify()#
Verify TLV blob message properties.
Creates a Verifier object that validates all key import parameters including key ID, algorithms, usage flags, type, size, lifetime, lifecycle, wrapping details, and cryptographic signatures.
- Return type:
Verifier- Returns:
Verifier object containing validation records for all TLV properties.
- wrap_and_sign(private_key, oem_import_mk_sk_key, srkh=None)#
Wrap private key and sign the Import Key message.
The method derives wrapping and CMAC keys using HKDF, wraps the private key using the specified algorithm (RFC3394 or AES-CBC), and generates a CMAC signature for the entire message.
- Parameters:
private_key (
bytes) – Unwrapped private key to be wrappedoem_import_mk_sk_key (
bytes) – OEM import master key for key derivationsrkh (
Optional[bytes]) – Super Root Key Hash used as salt for key derivation, defaults to None
- Raises:
SPSDKError – Invalid wrapping algorithm specified
- Return type:
None
- class spsdk.image.ahab.tlv.TLV#
Bases:
FeatureBaseClassTag-Length-Value (TLV) base class for AHAB image processing.
This abstract base class provides the foundation for handling TLV data structures in AHAB (Advanced High Assurance Boot) images. It manages TLV blob creation, parsing, validation, and configuration template generation across different MCU families.
- Variables:
NAME – TLV type identifier for the class.
FEATURE – Database feature reference for TLV blob operations.
-
FEATURE:
str= 'tlv_blob'#
- NAME = 'TLV_BLOB'#
- classmethod get_config_template(family)#
Get AHAB configuration template.
Generates a configuration template for the specified family by retrieving validation schemas and creating a commented configuration template.
- Parameters:
family (
FamilyRevision) – Family for which the template should be generated.- Return type:
str- Returns:
Configuration template as a string with comments and structure.
- classmethod get_tlv_class(name)#
Get the dedicated class for TLV by name.
Searches through all available TLV subclasses to find the one that matches the specified TLV type name.
- Parameters:
name (
str) – Name/label of the TLV type to find the corresponding class for.- Raises:
SPSDKValueError – When the specified TLV name is not supported.
- Return type:
Type[Self]- Returns:
The TLV subclass that corresponds to the given name.
- classmethod get_validation_schemas(family)#
Get list of validation schemas for TLV blob configuration.
The method retrieves and prepares validation schemas including the main TLV blob schema, family-specific schema, and general validation rules. It updates the family schema with supported families and the specified target family.
- Parameters:
family (
FamilyRevision) – Family revision for which the validation schema should be generated.- Return type:
list[dict[str,Any]]- Returns:
List containing output file schema, family schema, and TLV schema dictionaries.
- classmethod load_from_config(config)#
Create TLV object from configuration data.
Converts the configuration option into a TLV object by extracting the command from the configuration and instantiating the appropriate TLV class.
- Parameters:
config (
Config) – Message configuration dictionaries containing TLV command data.- Raises:
SPSDKError – Invalid config field command format.
- Return type:
Self- Returns:
TLV object instance based on the configuration command.
- classmethod parse(data)#
Parse object from bytes array.
This is an abstract method that must be implemented by child classes to define how to parse the specific TLV object from a byte array.
- Parameters:
data (
bytes) – Input bytes array to be parsed.- Raises:
SPSDKNotImplementedError – This method must be implemented in child class.
- Return type:
Self
- class spsdk.image.ahab.tlv.TLVTypes(tag, label, description=None)#
Bases:
SpsdkEnumTLV Types enumeration for AHAB image processing.
This enumeration defines the available Type-Length-Value (TLV) types used in AHAB (Advanced High Assurance Boot) image format for secure boot operations.
- KEY_IMPORT = (0, 'KEY_IMPORT', 'TLV for Key Import')#
Bootable image#
SPSDK Bootable Image management utilities.
This module provides functionality for creating, parsing, and manipulating bootable images across NXP MCU portfolio. It handles bootable image segments and provides the main BootableImage class for comprehensive image operations.
- class spsdk.image.bootable_image.bimg.BootableImage(family, mem_type, init_offset=0)#
Bases:
FeatureBaseClassBootable Image representation for NXP MCU devices.
This class manages the creation and manipulation of bootable images that can be programmed to various memory types on NXP MCU devices. It handles image segments, memory layout, and provides functionality for exporting complete bootable images.
- Variables:
FEATURE – Database feature identifier for bootable image support.
Bootable Image constructor.
Initialize a new bootable image instance for the specified chip family and memory type.
- Parameters:
family (
FamilyRevision) – Chip family and revision information.mem_type (
MemoryType) – Target memory type for the bootable image.init_offset (
Union[BootableImageSegment,int]) – Initial offset for the image, either as segment or integer value.
- Raises:
SPSDKValueError – When the specified memory type is not supported for the given family.
-
FEATURE:
str= 'bootable_image'#
- property bootable_header_only: bool#
Check if the image contains only bootable image header.
The method verifies whether the bootable image consists solely of the header without any application data by examining if all segments are either non-boot header segments with zero length or boot header segments.
- Returns:
True if image contains only bootable header, False otherwise.
- export()#
Export bootable image to binary format.
This method generates the complete binary representation of the bootable image by calling the export method on the image info object.
- Return type:
bytes- Returns:
Complete binary data of the bootable image.
- classmethod generate_extended_templates(family, template_name, output_dir, board=None, input_dir=None)#
Generate configuration templates based on template definition.
Creates YAML configuration files for bootable image and AHAB containers according to the template specification from the database.
- Parameters:
family (
FamilyRevision) – Target chip family and revision.template_name (
str) – Name of the template to generate.output_dir (
str) – Directory where template files will be created.board (
Optional[str]) – Optional board name to use board-specific filenames.input_dir (
Optional[str]) – Optional input directory path to prepend to filenames.
- Raises:
SPSDKError – When template generation fails.
- Return type:
list[str]- Returns:
List of generated file paths.
- classmethod get_board_filenames(family, board)#
Get board-specific filename mappings.
- Parameters:
family (
FamilyRevision) – Target chip family and revision.board (
str) – Board name to get filenames for.
- Raises:
SPSDKKeyError – When board doesn’t exist for the family.
- Return type:
dict[str,str]- Returns:
Dictionary mapping image types to filenames.
- get_config(data_path='./')#
Create configuration of the AHAB Image.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary.
- classmethod get_config_template(family, mem_type=MemoryType(tag=4, label='flexspi_nor', description='Flexspi NOR'))#
Get configuration template for the family.
The method generates a configuration template based on the validation schemas for the specified chip family and memory type.
- Parameters:
family (
FamilyRevision) – Chip family and revision information.mem_type (
MemoryType) – Memory type to use for template generation.
- Return type:
str- Returns:
Configuration template as a string.
- static get_memory_type_config(family, mem_type)#
Get memory type configuration for specific chip family and memory type.
The method retrieves configuration dictionary from the database for the specified memory type, ensuring it’s supported by the given chip family.
- Parameters:
family (
FamilyRevision) – Chip family revision to get configuration for.mem_type (
MemoryType) – Chip memory type to handle bootable area.
- Raises:
SPSDKKeyError – If memory type does not exist in database.
- Return type:
dict[str,Any]- Returns:
Dictionary with memory type configuration.
- get_segment(segment)#
Get bootable segment by its name or Enum class.
- Parameters:
segment (
Union[str,BootableImageSegment]) – Name of segment as string or BootableImageSegment enum value.- Raises:
SPSDKError – When the specified segment is not present in the bootable image.
- Return type:
- Returns:
The requested segment object.
- get_segment_offset(segment)#
Get segment offset within the bootable image.
Calculates the absolute offset of a segment within the bootable image. For segments with static offsets, returns the predefined value. For segments with dynamic offsets, computes the position based on previous segments and alignment requirements.
- Parameters:
segment (
Segment) – Segment object to get its offset from.- Raises:
SPSDKError – If segment is excluded from image or offset cannot be computed.
- Return type:
int- Returns:
Absolute offset of the segment within the bootable image.
- classmethod get_supported_boards(family)#
Get list of supported boards for a family.
- Parameters:
family (
FamilyRevision) – Target chip family and revision.- Return type:
list[str]- Returns:
List of board names available for the family.
- classmethod get_supported_memory_types(family=None)#
Get supported memory types for bootable images.
The method retrieves memory types either for a specific family from the database or all supported memory types across families if no family is specified.
- Parameters:
family (
Optional[FamilyRevision]) – Optional family revision to get memory types for specific family.- Return type:
list[MemoryType]- Returns:
List of supported memory types.
- static get_supported_revisions(family)#
Get supported revisions for a given family.
The method retrieves all available revisions for the specified family from the database manager, including only enabled revisions.
- Parameters:
family (
FamilyRevision) – Family revision object containing the family name.- Return type:
list[str]- Returns:
List of supported revision names for the given family.
- classmethod get_supported_templates(family)#
Get list of supported bootable image templates for a family.
- Parameters:
family (
FamilyRevision) – Target chip family and revision.- Return type:
list[str]- Returns:
List of template names available for the family.
- classmethod get_template_info(family, template_name)#
Get template configuration information.
- Parameters:
family (
FamilyRevision) – Target chip family and revision.template_name (
str) – Name of the template to retrieve.
- Raises:
SPSDKKeyError – When template doesn’t exist for the family.
- Return type:
dict[str,Any]- Returns:
Dictionary containing template configuration.
- classmethod get_validation_schemas(family, mem_type=None)#
Get validation schemas for bootable image configuration.
Retrieves and configures validation schemas specific to the given chip family and memory type, including family-specific settings and supported segments.
- Parameters:
family (
FamilyRevision) – Target chip family and revision.mem_type (
Optional[MemoryType]) – Memory type to be used for bootable image.
- Raises:
SPSDKValueError – When memory type parameter is not defined.
- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for configuration.
- classmethod get_validation_schemas_from_cfg(config)#
Get validation schemas based on configuration.
This method validates the basic configuration, extracts family, memory type, and initialization offset parameters, then creates a bootable image instance to retrieve the appropriate validation schemas.
- Parameters:
config (
Config) – Configuration object containing bootable image settings- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the specified configuration
- Raises:
SPSDKError – Invalid configuration or unsupported family/memory type combination
- property header_len: int#
Get the length of the bootable image header.
Calculates the length of the space before application data by finding the first non-boot header segment and returning its offset position.
- Raises:
SPSDKError – When unable to determine the size of bootable image header.
- Returns:
Length of the bootable image header in bytes.
- image_info()#
Create Binary image representation of the bootable image.
This method generates a BinaryImage object that contains information about all segments in the bootable image, including their offsets, sizes, and descriptions. It handles segment alignment and provides detailed information about the memory type and whether the image contains only headers or includes application data.
- Return type:
- Returns:
BinaryImage object containing structured information about the bootable image.
- property init_offset: int#
Get initial offset compared to “full” bootable image.
Only segments after this offset are considered.
- Returns:
Initial offset value.
- classmethod load_from_config(config)#
Load bootable image from configuration.
Creates a new bootable image instance by parsing the provided configuration data, including family revision, memory type, and initialization offset. Loads all available segments from the configuration.
- Parameters:
config (
Config) – Configuration data containing bootable image settings.- Raises:
SPSDKSegmentNotPresent – When a segment is not present in configuration.
- Return type:
Self- Returns:
New bootable image instance configured according to the provided settings.
- classmethod parse(binary, family=None, mem_type=None)#
Parse binary data into a bootable image object.
The method attempts to parse the provided binary data using all possible memory types and returns the first successful match. If multiple memory types are detected, a warning is logged and the first one is used.
- Parameters:
binary (
bytes) – Binary data of the bootable image to parse.family (
Optional[FamilyRevision]) – Target chip family revision, auto-detected if not specified.mem_type (
Optional[MemoryType]) – Specific memory type to use, auto-detected if not specified.
- Raises:
SPSDKError – When binary parsing fails for all memory types.
- Return type:
Self- Returns:
Parsed bootable image object.
- post_export(output_path)#
Perform post export operations on all segments.
Iterates through all segments in the bootable image and calls their post_export method if available, collecting any generated files.
- Parameters:
output_path (
str) – Directory path where post-export files should be created.- Return type:
list[str]- Returns:
List of file paths created during post-export operations.
- static pre_parse_verify(data, family, mem_type)#
Pre-parse binary to see main issues before parsing.
Performs verification of bootable image segments to identify potential parsing issues. The method attempts to parse the entire image first, and if that fails, tries parsing from different initial segment offsets to find a valid starting point.
- Parameters:
data (
bytes) – Bootable image binary data to be verified.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Memory type where the image will be stored.
- Raises:
SPSDKVerificationError – When verification of segments fails.
- Return type:
Verifier- Returns:
Verifier object containing pre-parse verification results.
- property segments: list[Segment]#
Get list of segments that are currently present in the bootable image.
This method filters the internal segments list to return only those segments that have the is_present flag set to True, indicating they contain actual data and are part of the bootable image.
- Returns:
List of segments that are present in the bootable image.
- set_init_offset(init_offset)#
Set init offset by name of segment or length.
The method allows setting the initialization offset either by providing a direct integer value or by specifying a bootable image segment. When a segment is provided, the method uses its full image offset as the init offset value.
- Parameters:
init_offset (
Union[BootableImageSegment,int]) – Either an integer offset value or a BootableImageSegment object whose offset will be used.- Raises:
SPSDKError – When the specified segment does not exist in the image.
- Return type:
None
- verify()#
Get verifier object for bootable image validation.
Creates a comprehensive verifier that validates the bootable image structure, including header information, segments, and binary layout. The verifier checks each segment’s availability and offset, validates the overall image structure, and provides detailed verification results.
- Raises:
SPSDKError – When binary structure validation fails.
- Return type:
Verifier- Returns:
Verifier object containing validation results for the bootable image.
Bootable image segments#
SPSDK bootable image segments management.
This module provides classes and utilities for handling various segments that compose bootable images across NXP MCU portfolio. It includes segment types for key blobs, FCB, image versions, key stores, BEE headers, XMCD, MBI, HAB, AHAB, and Secure Binary containers.
- class spsdk.image.bootable_image.segments.BootableImageSegment(tag, label, description=None)#
Bases:
SpsdkEnumBootable image segment type enumeration.
This enumeration defines the different types of segments that can be found in bootable images across NXP MCU portfolio, including security headers, containers, and image data segments.
- AHAB_CONTAINER = (11, 'ahab_container', 'AHAB container segment')#
- BEE_HEADER_0 = (6, 'bee_header_0', 'BEE header 0 segment')#
- BEE_HEADER_1 = (7, 'bee_header_1', 'BEE header 1 segment')#
- FCB = (2, 'fcb', 'Fcb segment')#
- HAB_CONTAINER = (10, 'hab_container', 'HAB container segment')#
- IMAGE_VERSION = (3, 'image_version', 'Image version segment')#
- IMAGE_VERSION_AP = (4, 'image_version_ap', 'Image version antipole segment')#
- KEYBLOB = (1, 'keyblob', 'Keyblob segment')#
- KEYSTORE = (5, 'keystore', 'Keystore segment')#
- MBI = (9, 'mbi', 'Masterboot image segment')#
- PRIMARY_IMAGE_CONTAINER_SET = (12, 'primary_image_container_set', 'Primary Image Container Set segment')#
- SB21 = (14, 'sb21', 'Secure binary 2.1 segment')#
- SB31 = (15, 'sb31', 'Secure binary 3.1 segment')#
- SECONDARY_IMAGE_CONTAINER_SET = (13, 'secondary_image_container_set', 'Secondary Image Container Set segment')#
- UNKNOWN = (0, 'unknown', 'Unknown segment')#
- XMCD = (8, 'xmcd', 'XMCD segment')#
- class spsdk.image.bootable_image.segments.Segment(offset, family, mem_type, raw_block=None)#
Bases:
BaseClassBase class for bootable image segments.
This class provides the foundation for all bootable image segments, managing segment data, positioning, and export functionality. Each segment represents a specific part of a bootable image with defined offset and memory type.
- Variables:
NAME – Segment type identifier from BootableImageSegment enumeration.
BOOT_HEADER – Flag indicating if segment requires boot header.
INIT_SEGMENT – Flag indicating if this is an initialization segment.
CFG_NAME – Configuration name for the segment type.
IMAGE_PATTERNS – Supported image patterns for segment generation.
OFFSET_ALIGNMENT – Required alignment for segment offset positioning.
Initialize a bootable image segment with basic properties.
Stores the segment’s position, target hardware configuration, and optional raw data for further processing in the bootable image creation workflow.
- Parameters:
offset (
int) – Offset of segment in the full bootable image.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Memory type where the segment will be stored.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.
-
ALT_NAME:
Optional[str] = None#
- BOOT_HEADER = True#
-
CFG_NAME:
Optional[str] = None#
- IMAGE_PATTERNS = ['zeros', 'ones']#
- INIT_SEGMENT = False#
- NAME = (0, 'unknown', 'Unknown segment')#
- OFFSET_ALIGNMENT = 1#
- classmethod cfg_key()#
Get configuration key name for the segment.
Returns the configuration key name used in configuration files. Falls back to the segment’s label name if no specific configuration name is defined.
- Return type:
str- Returns:
Configuration key name as string.
- clear()#
Clear the segment to init state.
This method resets the segment by setting the raw_block attribute to None, effectively returning the segment to its initial uninitialized state.
- Return type:
None
- create_config(output_dir)#
Create configuration and store segment data to specified directory.
Exports the segment data to a binary file in the output directory if the segment is present, otherwise returns an empty string.
- Parameters:
output_dir (
str) – Directory path where the segment data file should be stored.- Return type:
Union[str,int,dict]- Returns:
Filename of the created binary file or empty string if segment not present.
- export()#
Export object into bytes array.
- Return type:
bytes- Returns:
Raw binary block of segment if available, empty bytes otherwise.
- static find_segment_offset(binary)#
Find the start offset of a Segment in binary data.
This method searches through the provided binary data to locate where a Segment begins and returns the byte offset position.
- Parameters:
binary (
bytes) – Binary data to search for Segment start position.- Return type:
int- Returns:
Byte offset where the Segment begins in the data.
- property full_image_offset: int#
Get the offset of the segment within the full bootable image.
The method returns the aligned offset for positive values or the raw offset for negative values. The offset must be defined before calling this method.
- Raises:
SPSDKValueError – When segment offset is not defined.
- Returns:
Aligned offset for positive values, raw offset for negative values.
- image_info()#
Get image information in binary format.
Exports the segment content and wraps it in a BinaryImage object containing metadata such as name, size, and offset information.
- Return type:
- Returns:
The segment content wrapped in Binary Image format with metadata.
- property is_present: bool#
Check if the segment is present in the bootable image.
The segment is considered present when it’s not excluded and has exportable content.
- Returns:
True if segment is present and has content, False otherwise.
- load_config(config)#
Load segment from configuration.
The method loads a binary file specified in the configuration and assigns it to the raw_block attribute of the segment.
- Parameters:
config (
Config) – Configuration object containing segment settings and file paths.- Raises:
SPSDKSegmentNotPresent – When the segment is not present in config file.
SPSDKValueError – When the binary file path is invalid or cannot be loaded.
- Return type:
None
- classmethod parse(data)#
Parse object from bytes array.
- Parameters:
data (
bytes) – Input data to parse.- Raises:
NotImplementedError – Method must be implemented by subclass.
- Return type:
Self- Returns:
Parsed object instance.
- parse_binary(binary)#
Parse binary block into Segment object.
This method processes a binary block and populates the segment object with the parsed data. It validates the binary size against the expected segment size and checks for padding-only content.
- Parameters:
binary (
bytes) – Binary image data to be parsed into the segment.- Raises:
SPSDKParsingError – If given binary block size is smaller than expected segment size.
SPSDKSegmentNotPresent – If the input binary contains only padding bytes.
- Return type:
None
- post_export(output_path)#
Post export artifacts like fuse scripts.
This method handles the generation and export of additional artifacts that are created after the main export process, typically including fuse scripts or other configuration files.
- Parameters:
output_path (
str) – Path to export artifacts.- Return type:
list[str]- Returns:
List of post export artifacts (usually fuse scripts).
- pre_parse_verify(data)#
Pre-parse binary to validate data before full parsing.
The method performs initial validation of the bootable image binary data to identify potential issues before attempting full parsing operations.
- Parameters:
data (
bytes) – Bootable image binary data to be validated.- Return type:
Verifier- Returns:
Verifier object containing pre-parse validation results.
- property size: int#
Get the size of the segment.
- Returns:
Size of the segment in bytes, returns -1 if size cannot be determined.
- verify()#
Get verifier object of segment.
Creates and returns a Verifier instance that validates the segment’s properties including offset, size, and raw data integrity. The verifier checks for proper offset values, validates data size constraints, and ensures raw block data consistency.
- Return type:
Verifier- Returns:
Verifier object containing validation results for the current segment.
- class spsdk.image.bootable_image.segments.SegmentAhab(offset, family, mem_type, raw_block=None, ahab=None)#
Bases:
SegmentBootable Image Advanced High Assurance Boot (AHAB) Segment.
This class represents a segment containing AHAB container data within a bootable image. It manages AHAB-specific operations including parsing, validation, and export of AHAB containers used for secure boot processes in NXP MCUs.
- Variables:
NAME – Segment type identifier for AHAB containers.
BOOT_HEADER – Indicates this segment does not contain boot header.
INIT_SEGMENT – Marks this as an initialization segment.
Initialize AHAB segment with bootable image parameters.
The segment stores raw data and optional AHAB image, validating consistency between raw block and AHAB export data if both are provided.
- Parameters:
offset (
int) – Offset of segment in whole bootable image.family (
FamilyRevision) – Chip family revision identifier.mem_type (
MemoryType) – Target memory type for the segment.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.ahab (
Optional[AHABImage]) – Advanced High Assurance Boot image instance, defaults to None.
-
ALT_NAME:
Optional[str] = 'ahab_container'#
- BOOT_HEADER = False#
- INIT_SEGMENT = True#
- NAME = (11, 'ahab_container', 'AHAB container segment')#
- clear()#
Clear the segment to init state.
This method resets the segment to its initial state by calling the parent class clear method and setting the ahab attribute to None.
- Return type:
None
- create_config(output_dir)#
Create configuration and store data to specified path.
Generates configuration for the segment and writes AHAB configuration to YAML file if AHAB container is present.
- Parameters:
output_dir (
str) – Directory path where configuration files should be stored- Return type:
Union[str,int,dict]- Returns:
Relative path to generated configuration file or inherited value
- static find_segment_offset(binary)#
Find the start offset of AHAB Image in binary data.
The method locates the beginning position of an AHAB (Advanced High Assurance Boot) container within the provided binary data blob.
- Parameters:
binary (
bytes) – Binary data to search for AHAB container.- Return type:
int- Returns:
Byte offset position of the AHAB container in the binary data.
- image_info()#
Get image information in binary format.
Retrieves the segment content as a BinaryImage object. If AHAB (Advanced High Assurance Boot) is available, it uses AHAB’s image info with updated offset and name. Otherwise, falls back to the parent class implementation.
- Return type:
- Returns:
The segment content in Binary Image format with proper offset and name.
- load_config(config)#
Load segment from configuration.
The method attempts to load AHAB container from configuration first. If the configuration contains a sub-configuration for the segment, it loads and validates an AHAB image. If validation fails or no sub-configuration exists, it falls back to loading as binary data.
- Parameters:
config (
Config) – Configuration object containing segment data and settings.- Raises:
SPSDKSegmentNotPresent – When the segment is not present in config file.
SPSDKValueError – When AHAB container cannot be exported from configuration.
- Return type:
None
- parse_binary(binary)#
Parse binary block into AHAB Segment object.
The method validates the binary data contains a valid AHAB container header, parses it into an AHABImage object, and updates the segment’s internal state.
- Parameters:
binary (
bytes) – Binary image data containing AHAB container.- Raises:
SPSDKParsingError – When input binary block has zero length.
SPSDKSegmentNotPresent – When AHAB container header is not available or invalid.
- Return type:
None
- post_export(output_path)#
Execute post-export operations for the bootable image.
This method performs any necessary post-processing steps after the main export operation has completed. If AHAB (Advanced High Assurance Boot) is configured, it delegates the post-export handling to the AHAB component.
- Parameters:
output_path (
str) – Path where the exported image files are located.- Return type:
list[str]- Returns:
List of additional files created during post-export processing.
- pre_parse_verify(data)#
Pre-parse binary to see main issues before parsing.
Performs initial validation of the bootable image data by calling the parent class pre-parse verification and adding AHAB image specific verification.
- Parameters:
data (
bytes) – Bootable image binary data to be pre-parsed.- Return type:
Verifier- Returns:
Verifier object containing pre-parsed validation results.
- verify()#
Get verifier object of segment.
Verifies the current segment and includes AHAB container verification if present. The method performs hierarchical verification by adding child verifier results.
- Return type:
Verifier- Returns:
Verifier object containing validation results for the segment.
- class spsdk.image.bootable_image.segments.SegmentBeeHeader0(offset, family, mem_type, raw_block=None)#
Bases:
SegmentBootable Image BEE encryption header 0 segment.
This segment represents the first BEE (Bus Encryption Engine) header used for encryption configuration in bootable images. It provides a fixed-size header structure for BEE encryption parameters.
- Variables:
NAME – Segment identifier for BEE header 0.
Initialize a bootable image segment with basic properties.
Stores the segment’s position, target hardware configuration, and optional raw data for further processing in the bootable image creation workflow.
- Parameters:
offset (
int) – Offset of segment in the full bootable image.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Memory type where the segment will be stored.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.
- NAME = (6, 'bee_header_0', 'BEE header 0 segment')#
- property size: int#
Get the size of the keyblob segment.
- Returns:
Size of the keyblob segment in bytes (always 512).
- class spsdk.image.bootable_image.segments.SegmentBeeHeader1(offset, family, mem_type, raw_block=None)#
Bases:
SegmentBootable Image BEE encryption header 1 segment.
This segment represents the first header used in Bus Encryption Engine (BEE) encryption for bootable images, providing encryption metadata and configuration with a fixed size of 512 bytes.
- Variables:
NAME – Segment type identifier for BEE header 1.
Initialize a bootable image segment with basic properties.
Stores the segment’s position, target hardware configuration, and optional raw data for further processing in the bootable image creation workflow.
- Parameters:
offset (
int) – Offset of segment in the full bootable image.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Memory type where the segment will be stored.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.
- NAME = (7, 'bee_header_1', 'BEE header 1 segment')#
- property size: int#
Get the size of the keyblob segment.
- Returns:
Size of the keyblob segment in bytes (always 512).
- class spsdk.image.bootable_image.segments.SegmentFcb(offset, family, mem_type, raw_block=None, fcb=None)#
Bases:
SegmentBootable Image FCB Segment.
This class represents a Flash Configuration Block (FCB) segment within a bootable image. It manages FCB data including validation, parsing, and configuration for NXP MCU families that support FCB functionality.
- Variables:
NAME – Segment type identifier for FCB segments.
INIT_SEGMENT – Flag indicating this is an initialization segment.
Initialize FCB segment with offset and memory configuration.
The segment stores raw data and validates FCB block consistency if both raw data and FCB object are provided.
- Parameters:
offset (
int) – Offset of segment in whole bootable image.family (
FamilyRevision) – Chip family revision identifier.mem_type (
MemoryType) – Target memory type for the segment.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.fcb (
Optional[FCB]) – Flash Configuration Block object, defaults to None.
- Raises:
SPSDKParsingError – When FCB block doesn’t match the raw data.
- INIT_SEGMENT = True#
- NAME = (2, 'fcb', 'Fcb segment')#
- clear()#
Clear the segment to initial state.
This method resets the segment by calling the parent class clear method and setting the FCB (Flash Configuration Block) to None.
- Return type:
None
- create_config(output_dir)#
Create configuration and store data to specified path.
The method generates configuration data for the segment and optionally writes FCB configuration to a YAML file in the output directory.
- Parameters:
output_dir (
str) – Path where the configuration information should be stored- Return type:
Union[str,int,dict]- Returns:
Value of segment for configuration file
- property is_fcb_supported: bool#
Check if FCB is supported for the current family.
This property determines whether Flash Configuration Block (FCB) functionality is available for the chip family assigned to this segment.
- Returns:
True if FCB is supported for the current family, False otherwise.
- load_config(config)#
Load FCB segment from configuration.
Attempts to load FCB (Flash Configuration Block) segment from configuration, first trying to load from config structure, then falling back to binary file. Validates the FCB data and logs warnings for corrupted blocks.
- Parameters:
config (
Config) – Configuration object containing FCB segment settings.- Raises:
SPSDKSegmentNotPresent – When FCB segment is not present in config file.
- Return type:
None
- parse_binary(binary)#
Parse binary block into FCB Segment object.
The method attempts to parse the binary data as an FCB (Flash Configuration Block). It first checks if the binary contains valid FCB tags and if FCB is supported for the current family. If FCB is not present or parsing fails, appropriate exceptions are raised.
- Parameters:
binary (
bytes) – Binary image data to parse into FCB segment.- Raises:
SPSDKParsingError – If binary block is smaller than FCB size or parsing fails.
SPSDKSegmentNotPresent – If the input binary contains only padding bytes.
- Return type:
None
- property size: int#
Size of the segment in bytes.
Calculates the segment size based on FCB (Flash Configuration Block) support. If FCB is supported, returns the size of existing FCB or creates a new FCB to determine the size. Returns -1 for unsupported segments.
- Returns:
The segment size in bytes, or -1 if FCB is not supported.
- class spsdk.image.bootable_image.segments.SegmentHab(offset, family, mem_type, raw_block=None, hab=None)#
Bases:
SegmentBootable Image High Assurance Boot (HAB) Segment.
This class represents a HAB segment within a bootable image, managing High Assurance Boot container data and providing functionality for HAB image processing, validation, and export operations.
- Variables:
NAME – Segment type identifier for HAB container.
BOOT_HEADER – Indicates this segment does not contain boot header.
INIT_SEGMENT – Marks this as an initialization segment.
Initialize HAB segment with raw data and configuration.
The segment stores raw data and optionally validates it against HAB image patterns to ensure data integrity and proper formatting.
- Parameters:
offset (
int) – Offset of segment in whole bootable image.family (
FamilyRevision) – Chip family revision information.mem_type (
MemoryType) – Memory type used for the segment.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.hab (
Optional[HabImage]) – High Assurance Boot image instance for validation, defaults to None.
- BOOT_HEADER = False#
- INIT_SEGMENT = True#
- NAME = (10, 'hab_container', 'HAB container segment')#
- clear()#
Clear the segment to init state.
This method resets the segment to its initial state by calling the parent class clear method and setting the HAB (High Assurance Boot) attribute to None.
- Return type:
None
- image_info()#
Get image information in binary format.
Retrieves the segment content as a BinaryImage object. If HAB (High Assurance Boot) is available, uses HAB’s image info with updated offset and name. Otherwise, falls back to the parent class implementation.
- Return type:
- Returns:
The segment content in Binary Image format.
- load_config(config)#
Load segment from configuration.
Attempts to load HAB (High Assurance Boot) configuration first, then falls back to parent class configuration loading if HAB loading fails.
- Parameters:
config (
Config) – Configuration object containing segment data.- Raises:
SPSDKValueError – When HAB container cannot be exported from configuration.
- Return type:
None
- parse_binary(binary)#
Parse binary block into Segment object.
The method parses the provided binary data into a HAB (High Assurance Boot) image format and updates the segment’s internal state accordingly.
- Parameters:
binary (
bytes) – Binary image data to be parsed.- Raises:
SPSDKParsingError – When the input binary block has zero length.
- Return type:
None
- class spsdk.image.bootable_image.segments.SegmentImageVersion(offset, family, mem_type, raw_block=None)#
Bases:
SegmentBootable Image version segment.
This class represents a segment that stores version information for bootable images. It handles parsing, configuration, and verification of 4-byte version data with little-endian byte ordering.
- Variables:
NAME – Segment type identifier for image version segments.
Initialize a bootable image segment with basic properties.
Stores the segment’s position, target hardware configuration, and optional raw data for further processing in the bootable image creation workflow.
- Parameters:
offset (
int) – Offset of segment in the full bootable image.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Memory type where the segment will be stored.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.
- NAME = (3, 'image_version', 'Image version segment')#
- create_config(output_dir)#
Create configuration and extract segment value.
Extracts the first 4 bytes from the raw block data and converts them to an integer using little-endian byte order. Returns 0 if the segment is not present.
- Parameters:
output_dir (
str) – Path where the information should be stored.- Return type:
Union[str,int,dict]- Returns:
Integer value extracted from segment data, or 0 if segment not present.
- load_config(config)#
Load segment from configuration.
The method extracts configuration value using the segment’s configuration key, validates it as an integer, and converts it to raw bytes in little-endian format.
- Parameters:
config (
Config) – Configuration object containing segment settings.- Raises:
SPSDKValueError – Invalid configuration value (not an integer).
- Return type:
None
- parse_binary(binary)#
Parse binary block into Segment object.
The method extracts segment data from the provided binary based on the segment size and marks the segment as parsed.
- Parameters:
binary (
bytes) – Binary image data to parse.- Raises:
SPSDKParsingError – If given binary block size is not equal to block size in header.
- Return type:
None
- property size: int#
Get the size of the keyblob segment.
- Returns:
Size of the keyblob segment in bytes.
- verify()#
Get verifier object of segment.
Creates and returns a verifier object for the current segment, including validation of the image version from the raw block data if available.
- Return type:
Verifier- Returns:
Verifier object containing validation records for the current segment.
- class spsdk.image.bootable_image.segments.SegmentImageVersionAntiPole(offset, family, mem_type, raw_block=None)#
Bases:
SegmentBootable Image segment for image version with antipole value.
This segment manages image version data using an antipole encoding scheme where the version value and its bitwise complement are stored together for data integrity verification.
- Variables:
NAME – Segment identifier for bootable image processing.
CFG_NAME – Configuration key name for this segment type.
UNPROGRAMMED_VALUE – Default value for unprogrammed flash memory.
Initialize a bootable image segment with basic properties.
Stores the segment’s position, target hardware configuration, and optional raw data for further processing in the bootable image creation workflow.
- Parameters:
offset (
int) – Offset of segment in the full bootable image.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Memory type where the segment will be stored.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.
-
CFG_NAME:
Optional[str] = 'image_version'#
- NAME = (4, 'image_version_ap', 'Image version antipole segment')#
- UNPROGRAMMED_VALUE = 65535#
- create_config(output_dir)#
Create configuration and extract segment value.
The method extracts a 2-byte value from the raw block data in little-endian format. Returns 0 if the segment is not present.
- Parameters:
output_dir (
str) – Path where the information should be stored.- Return type:
Union[str,int,dict]- Returns:
Value of segment for configuration file (0 if not present, otherwise extracted value).
- load_config(config)#
Load segment from configuration.
The method loads image version from configuration and processes it into raw block data. If no configuration value is provided, uses unprogrammed values. The image version is stored with its complement in the upper 16 bits.
- Parameters:
config (
Config) – Configuration object containing segment settings.- Raises:
SPSDKValueError – Invalid configuration value (not an integer).
- Return type:
None
- parse_binary(binary)#
Parse binary block into Segment object.
The method validates the binary size against the segment requirements and stores the raw block data for further processing.
- Parameters:
binary (
bytes) – Binary image data to be parsed into segment.- Raises:
SPSDKParsingError – If given binary block size is smaller than required segment size.
- Return type:
None
- property size: int#
Get the size of the keyblob segment.
- Returns:
Size of the keyblob segment in bytes.
- verify()#
Verify the segment and return verifier object with validation results.
The method validates the image version by checking if the version and its antipole (bitwise inverse) match the expected pattern. It handles three cases: valid version pairs, unprogrammed default values, and mismatched version/antipole pairs.
- Return type:
Verifier- Returns:
Verifier object containing validation results for the segment.
- class spsdk.image.bootable_image.segments.SegmentKeyBlob(offset, family, mem_type, raw_block=None)#
Bases:
SegmentBootable Image KeyBlob Segment.
This segment represents a key blob section in bootable images, containing cryptographic keys and security data with a fixed size of 256 bytes.
- Variables:
NAME – Segment type identifier for keyblob segments.
Initialize a bootable image segment with basic properties.
Stores the segment’s position, target hardware configuration, and optional raw data for further processing in the bootable image creation workflow.
- Parameters:
offset (
int) – Offset of segment in the full bootable image.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Memory type where the segment will be stored.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.
- NAME = (1, 'keyblob', 'Keyblob segment')#
- property size: int#
Get the size of the keyblob segment.
- Returns:
Size of the keyblob segment in bytes (always 256).
- class spsdk.image.bootable_image.segments.SegmentKeyStore(offset, family, mem_type, raw_block=None)#
Bases:
SegmentBootable Image KeyStore Segment.
This class represents a keystore segment within a bootable image, managing cryptographic key storage with a fixed size allocation for security operations.
- Variables:
NAME – Segment type identifier for keystore segments.
Initialize a bootable image segment with basic properties.
Stores the segment’s position, target hardware configuration, and optional raw data for further processing in the bootable image creation workflow.
- Parameters:
offset (
int) – Offset of segment in the full bootable image.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Memory type where the segment will be stored.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.
- NAME = (5, 'keystore', 'Keystore segment')#
- property size: int#
Get the size of the keyblob segment.
- Returns:
Size of the keyblob segment in bytes (always 2048).
- class spsdk.image.bootable_image.segments.SegmentMbi(offset, family, mem_type, raw_block=None, mbi=None)#
Bases:
SegmentBootable Image Master Boot Image (MBI) Segment.
This class represents a segment containing Master Boot Image data within a bootable image. It manages MBI-specific operations including parsing, configuration, and export of MBI segments for NXP MCU bootable images.
- Variables:
NAME – Segment type identifier for MBI segments.
BOOT_HEADER – Indicates this segment is not a boot header.
INIT_SEGMENT – Marks this as an initialization segment.
Initialize MBI segment with offset and configuration data.
The segment stores raw data and optionally validates it against the provided Master Boot Image instance. If both raw_block and mbi are provided, they are compared for consistency.
- Parameters:
offset (
int) – Offset of segment in whole bootable image.family (
FamilyRevision) – Chip family revision identifier.mem_type (
MemoryType) – Target memory type for the segment.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.mbi (
Optional[MasterBootImage]) – Master Boot Image instance for validation, defaults to None.
- BOOT_HEADER = False#
- INIT_SEGMENT = True#
- NAME = (9, 'mbi', 'Masterboot image segment')#
- clear()#
Clear the segment to init state.
This method resets the segment to its initial state by calling the parent class clear method and setting the MBI (Master Boot Image) attribute to None.
- Return type:
None
- create_config(output_dir)#
Create configuration and store data to specified path.
The method generates configuration data for the segment and optionally creates an MBI configuration YAML file if an MBI object is present.
- Parameters:
output_dir (
str) – Directory path where configuration files should be stored.- Return type:
Union[str,int,dict]- Returns:
Configuration value for the segment.
- image_info()#
Get image information in binary format.
Retrieves the segment content as a BinaryImage object. If MBI (Master Boot Image) is available, exports the MBI image with proper offset and name. Otherwise, falls back to the parent class implementation.
- Return type:
- Returns:
The segment content in Binary Image format.
- load_config(config)#
Load segment from configuration.
Attempts to load MBI (Master Boot Image) from configuration first, falling back to binary loading if configuration parsing fails.
- Parameters:
config (
Config) – Configuration object containing segment data.- Raises:
SPSDKValueError – When MBI container cannot be exported from configuration.
- Return type:
None
- parse_binary(binary)#
Parse binary block into Segment object.
The method parses a binary image into a Master Boot Image (MBI) object, validates it, and stores the parsed data in the segment. Sets the parsing state accordingly.
- Parameters:
binary (
bytes) – Binary image data to be parsed.- Raises:
SPSDKParsingError – When the input binary block has zero length.
SPSDKError – When MBI parsing or validation fails.
- Return type:
None
- class spsdk.image.bootable_image.segments.SegmentPrimaryAhab(offset, family, mem_type, raw_block=None, ahab=None)#
Bases:
SegmentAhabPrimary Bootable Image Advanced High Assurance Boot (AHAB) Segment.
This class represents the primary image container set segment for AHAB-based bootable images, managing the primary boot container configuration and data.
- Variables:
NAME – Segment identifier for primary image container set.
CFG_NAME – Configuration name with fallback support for backward compatibility.
Initialize AHAB segment with bootable image parameters.
The segment stores raw data and optional AHAB image, validating consistency between raw block and AHAB export data if both are provided.
- Parameters:
offset (
int) – Offset of segment in whole bootable image.family (
FamilyRevision) – Chip family revision identifier.mem_type (
MemoryType) – Target memory type for the segment.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.ahab (
Optional[AHABImage]) – Advanced High Assurance Boot image instance, defaults to None.
-
ALT_NAME:
Optional[str] = 'spl'#
- NAME = (12, 'primary_image_container_set', 'Primary Image Container Set segment')#
- class spsdk.image.bootable_image.segments.SegmentSB21(offset, family, mem_type, raw_block=None, sb21=None)#
Bases:
SegmentBootable Image Secure Binary 2.1 Segment class.
This class represents a segment containing Secure Binary v2.1 data within a bootable image. It handles loading, parsing, and management of SB2.1 format data, supporting both configuration-based initialization and raw binary data processing.
- Variables:
NAME – Segment type identifier for SB2.1 segments.
BOOT_HEADER – Indicates this segment does not contain boot header.
INIT_SEGMENT – Indicates this is an initialization segment.
Initialize Segment with bootable image data.
Segment initialization requires at least raw data to be stored. The method also supports initialization with Secure Binary v2.1 data and validates consistency between raw block and SB21 export data.
- Parameters:
offset (
int) – Offset of Segment in whole bootable image.family (
FamilyRevision) – Chip family.mem_type (
MemoryType) – Used memory type.raw_block (
Optional[BinaryImage]) – Raw data of segment.sb21 (
Optional[BootImageV21]) – Secure Binary v2.1 class.
- BOOT_HEADER = False#
- INIT_SEGMENT = True#
- NAME = (14, 'sb21', 'Secure binary 2.1 segment')#
- clear()#
Clear the segment to initial state.
This method resets the segment by calling the parent class clear method and setting the sb21 attribute to None.
- Return type:
None
- load_config(config)#
Load segment from configuration.
Loads SB2.1 (Secure Binary 2.1) segment from configuration data. First attempts to load as SB2.1 configuration, then falls back to binary loading if configuration parsing fails.
- Parameters:
config (
Config) – Configuration object containing segment data.- Raises:
SPSDKValueError – When SB2.1 cannot be exported from the configuration.
- Return type:
None
- parse_binary(binary)#
Parse binary block into Segment object.
This method validates the binary header using BootImageV21 validation and then delegates the actual parsing to the parent class implementation.
- Parameters:
binary (
bytes) – Binary image data to be parsed into segment structure.- Raises:
SPSDKError – Invalid binary header format or parsing failure.
- Return type:
None
- class spsdk.image.bootable_image.segments.SegmentSB31(offset, family, mem_type, raw_block=None, sb31=None)#
Bases:
SegmentBootable Image Secure Binary 3.1 Segment class.
This class represents a segment containing Secure Binary v3.1 data within a bootable image. It handles loading, parsing, and management of SB3.1 segments including configuration-based initialization and binary data processing.
- Variables:
NAME – Segment type identifier for SB3.1 segments.
BOOT_HEADER – Indicates this segment type does not contain boot header.
INIT_SEGMENT – Indicates this segment requires initialization.
Initialize segment with bootable image data and secure binary configuration.
- Parameters:
offset (
int) – Offset of segment in whole bootable image.family (
FamilyRevision) – Chip family revision identifier.mem_type (
MemoryType) – Target memory type for the segment.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.sb31 (
Optional[SecureBinary31]) – Secure Binary v3.1 configuration object, defaults to None.
- BOOT_HEADER = False#
- INIT_SEGMENT = True#
- NAME = (15, 'sb31', 'Secure binary 3.1 segment')#
- clear()#
Clear the segment to init state.
This method resets the segment to its initial state by calling the parent class clear method and setting the sb31 attribute to None.
- Return type:
None
- load_config(config)#
Load segment from configuration.
Attempts to load SB3.1 (Secure Binary 3.1) from configuration first, falling back to binary loading if configuration parsing fails.
- Parameters:
config (
Config) – Configuration object containing segment data.- Raises:
SPSDKValueError – When SB3.1 cannot be exported from the configuration.
- Return type:
None
- parse_binary(binary)#
Parse binary block into Segment object.
This method validates the binary header and delegates parsing to the parent class implementation while marking the segment as not parsed initially.
- Parameters:
binary (
bytes) – Binary image data to be parsed into segment structure.- Raises:
SPSDKError – Invalid binary header format.
- Return type:
None
- class spsdk.image.bootable_image.segments.SegmentSecondaryAhab(offset, family, mem_type, raw_block=None, ahab=None)#
Bases:
SegmentAhabSecondary Bootable Image Advanced High Assurance Boot (AHAB) Segment class.
This class manages secondary AHAB container segments in bootable images, handling configuration loading and creation with custom offset management for secondary image containers.
- Variables:
NAME – Segment type identifier for secondary image container set.
CFG_NAME – Configuration name with fallback support for backward compatibility.
OFFSET_ALIGNMENT – Required alignment boundary of 1024 bytes.
INIT_SEGMENT – Flag indicating this is not an initialization segment.
Initialize AHAB segment with bootable image parameters.
The segment stores raw data and optional AHAB image, validating consistency between raw block and AHAB export data if both are provided.
- Parameters:
offset (
int) – Offset of segment in whole bootable image.family (
FamilyRevision) – Chip family revision identifier.mem_type (
MemoryType) – Target memory type for the segment.raw_block (
Optional[BinaryImage]) – Raw binary image data of the segment, defaults to None.ahab (
Optional[AHABImage]) – Advanced High Assurance Boot image instance, defaults to None.
-
ALT_NAME:
Optional[str] = 'uboot'#
- INIT_SEGMENT = False#
- NAME = (13, 'secondary_image_container_set', 'Secondary Image Container Set segment')#
- OFFSET_ALIGNMENT = 1024#
- create_config(output_dir)#
Create configuration and store data to specified path.
The method generates configuration data for the segment and optionally includes offset information if the segment is not positioned right behind the previous segment.
- Parameters:
output_dir (
str) – Path where the segment information should be stored.- Return type:
Union[str,int,dict]- Returns:
Configuration value - either basic segment data or dictionary with path and offset.
- load_config(config)#
Load segment from configuration.
This method extracts segment configuration data, processes offset if present, and delegates path processing to the parent class.
- Parameters:
config (
Config) – Configuration object containing segment settings including optional offset and path.- Return type:
None
- class spsdk.image.bootable_image.segments.SegmentXmcd(offset, family, mem_type, raw_block=None, xmcd=None)#
Bases:
SegmentBootable Image XMCD Segment class.
This class represents an External Memory Configuration Data (XMCD) segment within a bootable image, providing functionality to parse, validate, and manage XMCD configuration data for external memory initialization.
- Variables:
NAME – Segment type identifier for XMCD segments.
Initialize XMCD segment with configuration data.
The segment stores XMCD (eXternal Memory Configuration Data) block that contains memory configuration parameters for external memory initialization.
- Parameters:
offset (
int) – Offset of segment in whole bootable image.family (
FamilyRevision) – Target chip family and revision information.mem_type (
MemoryType) – Type of memory where segment will be stored.raw_block (
Optional[BinaryImage]) – Raw binary data of the segment, optional.xmcd (
Optional[XMCD]) – XMCD configuration object, optional.
- Raises:
SPSDKParsingError – When XMCD block doesn’t match provided raw data.
- NAME = (8, 'xmcd', 'XMCD segment')#
- clear()#
Clear the segment to init state.
This method resets the segment to its initial state by calling the parent class clear method and setting the xmcd attribute to None.
- Return type:
None
- create_config(output_dir)#
Create configuration and store data to specified path.
The method creates configuration data by calling the parent class method and additionally writes XMCD configuration to a YAML file if XMCD data exists.
- Parameters:
output_dir (
str) – Directory path where the configuration files should be stored.- Return type:
Union[str,int,dict]- Returns:
Configuration value for the segment.
- load_config(config)#
Load segment from configuration.
The method attempts to load XMCD from configuration first. If XMCD loading fails, it falls back to the parent class loading method.
- Parameters:
config (
Config) – Configuration object containing segment data.- Raises:
SPSDKSegmentNotPresent – When XMCD segment is not present in config file.
SPSDKError – When configuration loading fails.
- Return type:
None
- parse_binary(binary)#
Parse binary block into XMCD Segment object.
The method parses the input binary data to create an XMCD (External Memory Configuration Data) segment. It validates the binary size and checks for padding bytes to ensure valid XMCD data is present.
- Parameters:
binary (
bytes) – Binary image data to parse into XMCD segment.- Raises:
SPSDKParsingError – If given binary block size is smaller than required XMCD size.
SPSDKSegmentNotPresent – If the input binary contains only padding bytes.
- Return type:
None
- property size: int#
Get keyblob segment size.
- Returns:
Size of the keyblob segment in bytes (always 512).
- verify()#
Get verifier object of segment.
Performs verification of the segment and includes XMCD verification if present.
- Return type:
Verifier- Returns:
Verifier object containing validation results for current segment.
- spsdk.image.bootable_image.segments.get_segment_class(name)#
Get the segment class type for a bootable image segment.
- Parameters:
name (
BootableImageSegment) – The bootable image segment identifier.- Raises:
SPSDKValueError – Unsupported bootable image segment name.
- Return type:
Type[Segment]- Returns:
Segment class type.
- spsdk.image.bootable_image.segments.get_segments()#
Get dictionary of all supported bootable image segments.
This method dynamically discovers all segment classes that inherit from the base Segment class by inspecting the global namespace and filtering for valid segment implementations.
- Return type:
dict[BootableImageSegment,Type[Segment]]- Returns:
Dictionary mapping segment names to their corresponding segment class types.
FCB - Flash Configuration Block#
SPSDK Flash Configuration Block (FCB) management utilities.
This module provides functionality for handling Flash Configuration Blocks, which contain essential flash memory configuration parameters for NXP MCUs. The FCB class enables creation, validation, and manipulation of flash configuration data required for proper boot sequence initialization.
- class spsdk.image.fcb.fcb.FCB(family, mem_type)#
Bases:
SegmentBaseFCB (Flash Configuration Block) segment for NXP MCU images.
This class represents a Flash Configuration Block that contains memory-specific configuration data for NXP microcontrollers. The FCB provides essential parameters for proper flash memory initialization and operation.
- Variables:
FEATURE – Database feature identifier for FCB operations.
TAG – Binary tag identifier for FCB segments.
TAG_SWAPPED – Byte-swapped version of the FCB tag.
FCB Constructor.
Initialize FCB (Flash Configuration Block) for specified chip family and memory type.
- Parameters:
family (
FamilyRevision) – Chip family and revision information.mem_type (
MemoryType) – Memory type to be used for FCB configuration.
- Raises:
SPSDKValueError – Unsupported family or memory type for the given family.
- FEATURE: str = 'fcb'#
- PRE_VALIDATION_CFG_HOOK = <spsdk.utils.registers.RegistersPreValidationHook object>#
- TAG = b'FCFB'#
- TAG_SWAPPED = b'CFBF'#
- get_config(data_path='./')#
Create configuration of the FCB.
The method generates a configuration dictionary containing family information, revision, memory type, and FCB register settings that can be used for FCB reconstruction.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration object with FCB settings.
- classmethod get_config_template(family, mem_type=MemoryType(tag=4, label='flexspi_nor', description='Flexspi NOR'))#
Get configuration template for selected family and memory type.
Generates a configuration template for FCB (Flash Configuration Block) based on the specified family revision and memory type parameters.
- Parameters:
family (
FamilyRevision) – Family revision specification for target MCU.mem_type (
MemoryType) – Memory type to generate configuration for.
- Return type:
str- Returns:
Template string of FCB Block configuration.
- classmethod get_validation_schemas(family, mem_type=MemoryType(tag=4, label='flexspi_nor', description='Flexspi NOR'))#
Create the validation schema for Flash Configuration Block.
The method generates validation schemas for FCB configuration based on the specified family and memory type. It combines family-specific settings with memory type configurations and FCB register schemas.
- Parameters:
family (
FamilyRevision) – Family description specifying the target MCU family.mem_type (
MemoryType) – Used memory type for the FCB configuration.
- Raises:
SPSDKError – Family or revision is not supported.
- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas containing family, memory type, and FCB schemas.
- static get_validation_schemas_basic()#
Create the validation schema for FCB supported families.
The method generates validation schemas by combining family-specific schema with memory type schema, filtering only for families supported by FCB.
- Return type:
list[dict[str,Any]]- Returns:
List containing family validation schema and memory type schema for FCB.
- classmethod get_validation_schemas_from_cfg(config)#
Get validation schemas based on configuration.
This method validates the basic configuration, extracts family and memory type information, and returns the appropriate validation schemas for the FCB.
- Parameters:
config (
Config) – Configuration object containing family and memory type settings- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the specified configuration
- Raises:
SPSDKError – Invalid configuration or unsupported family/memory type combination
- classmethod load_from_config(config)#
Load FCB object from configuration.
Creates and initializes a Flexible Configuration Block (FCB) object from the provided configuration data, including family revision, memory type, and FCB-specific settings.
- Parameters:
config (
Config) – Configuration dictionary containing FCB parameters.- Raises:
SPSDKValueError – Invalid configuration data or missing required parameters.
- Return type:
Self- Returns:
Initialized FCB object with loaded configuration settings.
- classmethod parse(binary, offset=0, family=Unknown, Revision: latest, mem_type=MemoryType(tag=4, label='flexspi_nor', description='Flexspi NOR'))#
Parse binary block into FCB object.
Parses a binary data block to create an FCB (Flash Configuration Block) object. The method automatically detects and corrects byte order swapping if needed.
- Parameters:
binary (
bytes) – Binary image data to parse.offset (
int) – Offset position of FCB in the binary image.family (
FamilyRevision) – Target chip family revision.mem_type (
MemoryType) – Memory type used for the FCB.
- Raises:
SPSDKError – If binary block size is insufficient or contains invalid FCB tag.
- Return type:
Self- Returns:
Parsed FCB object instance.
- property registers: Registers#
Get the registers of the FCB segment.
- Returns:
Registers object containing the FCB configuration registers.
- property size: int#
Get the size of the segment in bytes.
- Returns:
The segment size in bytes.
HAB - High Assurance Boot#
SPSDK HAB (High Assurance Boot) support module.
This module provides functionality for working with NXP’s High Assurance Boot security feature, including HAB container handling, signature verification, and secure boot implementation across supported NXP MCU devices.
HAB Container#
SPSDK HAB (High Assurance Boot) image container management.
This module provides functionality for creating, manipulating, and managing HAB image containers used in NXP’s secure boot process. It includes support for boot device configuration and HAB image operations.
- class spsdk.image.hab.hab_image.BootDevice(tag, label, description=None)#
Bases:
SpsdkEnumHAB boot device enumeration.
Enumeration of supported boot devices for High Assurance Boot (HAB) image configuration, defining the storage medium from which the bootloader loads the application image.
- FLEXSPI_NAND = (1, 'flexspi_nand')#
- FLEXSPI_NOR = (0, 'flexspi_nor')#
- MMC = (4, 'mmc')#
- SD = (3, 'sd')#
- SEMC_NAND = (2, 'semc_nand')#
- SERIAL_DOWNLOADER = (5, 'serial_downloader')#
- class spsdk.image.hab.hab_image.HabImage(family, flags, start_address, segments, boot_device=None, ivt_offset=None, image_pattern='zeros')#
Bases:
FeatureBaseClassHAB (High Assurance Boot) image representation for NXP MCUs.
This class manages HAB-enabled bootable images including IVT (Image Vector Table) configuration, segments management, and security features like authentication and encryption for secure boot operations.
- Variables:
FEATURE – Database feature identifier for HAB functionality.
Initialize HAB (High Assurance Boot) image.
Creates a new HAB image instance with specified configuration parameters including family revision, boot flags, memory addresses, and image segments.
- Parameters:
family (
FamilyRevision) – Target MCU family and revision information.flags (
int) – Boot flags controlling image behavior.start_address (
int) – Start address of bootable image in memory.segments (
list[HabSegmentBase]) – List of HAB segments to include in the image.boot_device (
Optional[BootDevice]) – Optional boot device specification.ivt_offset (
Optional[int]) – Optional IVT offset value which is actually the HAB image offset.image_pattern (
str) – Image pattern used to fill empty spaces, defaults to “zeros”.
-
FEATURE:
str= 'hab'#
- property app_segment: HabSegmentApp#
Get APP segment object from the HAB image.
Retrieves the application segment from the HAB image segments collection. The APP segment contains the main application code and data.
- Raises:
SPSDKSegmentNotPresent – When APP segment is not present in the image.
- Returns:
The application segment object.
- property bdt_segment: HabSegmentBDT#
Get BDT segment object from the HAB image.
Retrieves the Boot Data Table (BDT) segment from the current HAB image segments.
- Raises:
SPSDKSegmentNotPresent – When BDT segment is not present in the image.
- Returns:
BDT segment object containing boot data table information.
- property csf_segment: HabSegmentCSF | None#
Get CSF segment object if it exists.
- Returns:
CSF segment object if exists, None otherwise.
- property dcd_segment: HabSegmentDcd | None#
Get DCD segment object if it exists.
- Returns:
DCD segment object if exists, None otherwise.
- export()#
Export the HAB image into binary format.
- Return type:
bytes- Returns:
Binary representation of the HAB image.
- export_padding()#
Export image as binary data with initial padding included.
- Return type:
bytes- Returns:
Binary representation of the image including padding.
- static get_boot_devices(family)#
Get all supported boot devices for given family.
The method retrieves boot device information from the database for the specified family and returns a list of BootDevice objects created from the available memory types.
- Parameters:
family (
FamilyRevision) – Target family revision to get boot devices for.- Return type:
list[BootDevice]- Returns:
List of supported boot devices for the specified family.
- get_config(data_path='./')#
Create configuration of the HAB image feature.
The method generates a configuration object containing options like flags, family information, revision, and optional file paths for XMCD and DCD segments based on the current state.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration object with HAB image settings.
- classmethod get_config_template(family)#
Generate HAB configuration template.
Creates a configuration template for Hardware Abstraction Boot (HAB) image based on the specified family revision and validation schemas.
- Parameters:
family (
FamilyRevision) – Target MCU family and revision for template generation.- Return type:
str- Returns:
Configuration template as a string with proper formatting and comments.
- get_segment(segment)#
Get image’s segment by segment type.
Searches through all segments in the image to find the one matching the specified segment identifier.
- Parameters:
segment (
HabSegmentEnum) – Segment enum specifying which segment type to retrieve.- Return type:
Optional[HabSegmentBase]- Returns:
The matching segment if found, None otherwise.
- get_supported_boot_devices()#
Get supported boot devices for this HAB image.
This method retrieves the list of boot devices (target memories) that are supported for the current family configuration.
- Return type:
list[BootDevice]- Returns:
List of supported boot devices for the current family.
- classmethod get_validation_schemas(family)#
Create the list of validation schemas for HAB image configuration.
The method generates validation schemas based on the specified family revision, including HAB options, input configurations, and sections. It dynamically updates the schema with supported families and available boot devices for the given family.
- Parameters:
family (
FamilyRevision) – Family revision to generate schemas for.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for HAB image configuration.
- classmethod get_validation_schemas_from_cfg(config)#
Get validation schemas based on configuration.
This method extracts options from the configuration, validates them against basic schemas, loads the family revision information, and returns the appropriate validation schemas for the specified family.
- Parameters:
config (
Config) – Valid configuration object containing options and family information.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the specified family.
- image_info(padding=False)#
Create Binary image of HAB image.
The method creates a BinaryImage object containing all segments of the HAB image with proper offsets and binary data.
- Parameters:
padding (
bool) – If True, adds IVT offset to segment offsets for proper alignment.- Return type:
- Returns:
BinaryImage object containing the complete HAB image structure.
- property is_authenticated: bool#
Check if the image is authenticated.
The method examines the authentication flag in the image flags field by extracting bits 3-0 and checking bit 3 specifically.
- Returns:
True if image is authenticated, False otherwise.
- property is_encrypted: bool#
Check if the HAB image is encrypted.
- Returns:
True if image is encrypted, False otherwise.
- property ivt_offset: int#
Get the IVT (Image Vector Table) offset for the HAB image.
The method retrieves the IVT offset from either a cached value or from the database based on the boot device configuration. The IVT offset is required for proper HAB image formatting and boot sequence.
- Raises:
SPSDKError – When IVT offset cannot be determined (no cached value and no boot device).
- Returns:
The IVT offset value in bytes.
- property ivt_segment: HabSegmentIvt#
Get IVT segment object from the HAB image.
Retrieves the Image Vector Table (IVT) segment from the current HAB image segments. The IVT segment contains essential boot information and must be present in valid HAB images.
- Raises:
SPSDKSegmentNotPresent – When the IVT segment is not found in the image.
- Returns:
The IVT segment object containing boot vector information.
- classmethod load_from_config(config)#
Load the HAB image object from parsed configuration.
Creates a HAB image by loading all available segments and configuring the image with the specified options including family, flags, IVT offset, and start address.
- Parameters:
config (
Config) – Image configuration containing segments and options data.- Return type:
Self- Returns:
Configured HAB image object with loaded segments.
- classmethod parse(data, family=Unknown, Revision: latest)#
Parse existing binary into HAB image object.
The method analyzes binary data to extract HAB segments and constructs a HAB image object with proper IVT offset, start address, and segment configuration.
- Parameters:
data (
bytes) – Binary data to be parsed into HAB image segments.family (
FamilyRevision) – Target chip family revision for parsing context.
- Return type:
Self- Returns:
HAB image object constructed from parsed binary data.
- Raises:
AssertionError – When required IVT or BDT segments are not found.
- post_export(output_path)#
Perform post export steps for all segments in the HAB image.
This method iterates through all segments in the image and executes their post-export operations, collecting any generated files from each segment.
- Parameters:
output_path (
str) – Directory path where post-export files should be generated.- Return type:
list[str]- Returns:
List of file paths that were generated during post-export operations.
- classmethod transform_bd_configuration(config)#
Transform configuration from flat structure to BD structure.
Converts a flat configuration structure from the BD parser into a structured format with sections containing IDs, options, and commands. Maps section names to their corresponding numeric identifiers and restructures the data for further processing.
- Parameters:
config (
Config) – Parsed configuration from BD parser containing sections and input image file.- Return type:
Config- Returns:
Transformed configuration with structured sections and sources.
- classmethod transform_configuration(config)#
Transform configuration from BD parser to flat YAML structure.
Converts section IDs to human-readable names and flattens the options structure for easier YAML representation. Maps numeric section identifiers to their corresponding command names and extracts options into a simplified format.
- Parameters:
config (
dict[Any,Any]) – Parsed configuration dictionary from BD parser containing sections and source file information- Return type:
dict[Any,Any]- Returns:
Transformed configuration with named sections and flattened structure
- update_csf()#
Update the CSF segment including signing and encryption.
This method handles the complete CSF (Command Sequence File) segment update process, including encryption of application data when encryption is enabled and signature updates when authentication is enabled. It modifies the BDT segment length for encrypted images and processes the image data accordingly.
- Raises:
SPSDKError – When CSF segment is missing but encryption is enabled.
- Return type:
None
- verify()#
Verify HAB image data and return verification results.
This method performs comprehensive verification of the High Assurance Boot (HAB) image, including validation of flags, IVT offset, and all image segments. It checks for custom IVT offsets and validates flag values against expected ranges.
- Return type:
Verifier- Returns:
Verifier object containing detailed verification results and any warnings or errors.
- property xmcd_segment: HabSegmentXMCD | None#
Get XMCD segment object from the HAB image.
Retrieves the XMCD (External Memory Configuration Data) segment if it exists in the current HAB image.
- Returns:
XMCD segment object if present, None otherwise.
XMCD#
SPSDK External Memory Configuration Data (XMCD) management utilities.
This module provides functionality for creating, parsing, and managing XMCD blocks used to configure external memory interfaces in NXP MCUs. It includes support for different configuration block types and CRC validation.
- class spsdk.image.xmcd.xmcd.ConfigurationBlockType(tag, label, description=None)#
Bases:
SpsdkEnumXMCD configuration block type enumeration.
Defines the supported types of configuration blocks for XMCD (External Memory Configuration Data) including simplified and full configuration options.
- FULL = (1, 'full', 'Full configuration')#
- SIMPLIFIED = (0, 'simplified', 'Simplified configuration')#
- class spsdk.image.xmcd.xmcd.XMCD(family, mem_type, config_type)#
Bases:
SegmentBaseXMCD (External Memory Configuration Data) segment.
This class manages external memory configuration data for NXP MCUs, providing functionality to create, validate, and export XMCD segments. It handles different memory types and configuration block types (simplified or full) with automatic register management and CRC calculation.
- Variables:
FEATURE – Database feature identifier for XMCD operations.
Initialize XMCD (External Memory Configuration Data) instance.
Creates an XMCD object for specific chip family, memory type, and configuration block type. Initializes internal registers based on the provided parameters.
- Parameters:
family (
FamilyRevision) – Chip family and revision information.mem_type (
MemoryType) – Type of external memory to configure.config_type (
ConfigurationBlockType) – Configuration block type (simplified or full).
- Raises:
SPSDKKeyError – Unsupported combination of memory type and configuration type.
-
FEATURE:
str= 'xmcd'#
- calculate_crc()#
Calculate XMCD CRC value.
Computes the CRC32 MPEG checksum for the XMCD data using the exported binary representation of the XMCD structure.
- Return type:
bytes- Returns:
4-byte CRC value in big-endian format.
- property crc: bytes#
Get CRC value of XMCD object.
- Returns:
CRC value as bytes.
- create_crc_hash_fuses_script()#
Create fuses script of CRC hash.
Generates a fuse script for programming CRC hash values into the device fuses. The method handles cases where CRC hash fuses are not available for the specified family.
- Return type:
str- Returns:
Fuse script content as string, or error message if CRC hash fuses are not available.
- get_config(data_path='./')#
Create configuration of the XMCD.
The method generates a configuration dictionary containing family information, memory type, configuration type, and XMCD register settings.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary with XMCD settings.
- classmethod get_config_template(family, mem_type=MemoryType(tag=0, label='flexspi_ram', description='FlexSPI RAM'), config_type=ConfigurationBlockType(tag=1, label='full', description='Full configuration'))#
Generate configuration template for selected family and memory type.
- Parameters:
family (
FamilyRevision) – Family description specifying the target MCU family.mem_type (
MemoryType) – Used memory type, defaults to FLEXSPI_RAM.config_type (
ConfigurationBlockType) – Configuration type - either simplified or full block type.
- Return type:
str- Returns:
Template of XMCD Block configuration as string.
- classmethod get_supported_configuration_types(family, mem_type)#
Get supported configuration types for given family and memory type.
The method retrieves available configuration block types from the database for the specified family and memory type combination.
- Parameters:
family (
FamilyRevision) – Target MCU family and revision.mem_type (
MemoryType) – Memory type to get configuration types for.
- Return type:
list[ConfigurationBlockType]- Returns:
List of supported configuration block types.
- classmethod get_validation_schemas(family, mem_type=MemoryType(tag=4, label='flexspi_nor', description='Flexspi NOR'), config_type=ConfigurationBlockType(tag=0, label='simplified', description='Simplified configuration'))#
Create the validation schema for XMCD configuration.
This method generates validation schemas for External Memory Configuration Data based on the specified family, memory type, and configuration type. It updates the schema with supported options and creates register validation schemas.
- Parameters:
family (
FamilyRevision) – Family description specifying the target MCU family.mem_type (
MemoryType) – Used memory type for the configuration.config_type (
ConfigurationBlockType) – Configuration type, either simplified or full.
- Raises:
SPSDKError – Family or revision is not supported.
- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas for XMCD configuration.
- classmethod get_validation_schemas_basic()#
Create the validation schema just for supported families.
The method generates validation schemas for XMCD configuration by combining family validation schema with memory type and config type schemas. It updates the family schema to include only the families supported by XMCD.
- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas containing family, memory type, and config type schemas for XMCD supported families.
- classmethod get_validation_schemas_from_cfg(config)#
Get validation schemas based on configuration.
This method validates the basic configuration structure, extracts family revision, memory type, and configuration block type from the config, then returns the appropriate validation schemas for those parameters.
- Parameters:
config (
Config) – Valid configuration object containing family, memory type, and config type.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the specified configuration.
- classmethod load_from_config(config)#
Load XMCD object from configuration.
Creates and initializes an XMCD (External Memory Configuration Data) object from the provided configuration settings including family, memory type, configuration type, and register settings.
- Parameters:
config (
Config) – Configuration object containing XMCD settings.- Raises:
SPSDKValueError – Invalid configuration values or missing required fields.
- Return type:
Self- Returns:
Initialized XMCD object with loaded configuration.
- classmethod parse(binary, offset=0, family=Unknown, Revision: latest)#
Parse binary block into XMCD object.
This method creates an XMCD instance by parsing the provided binary data, starting from the specified offset. It first parses and verifies the XMCD header, then creates the object with the appropriate configuration.
- Parameters:
binary (
bytes) – Binary image containing XMCD data.offset (
int) – Offset of XMCD in binary image.family (
FamilyRevision) – Chip family revision information.
- Raises:
SPSDKError – If given binary block size is not equal to block size in header.
- Return type:
Self- Returns:
Parsed XMCD object instance.
- static pre_parse_verify(data, family)#
Pre-parse verify of XMCD data.
Performs initial verification of XMCD (External Memory Configuration Data) binary data by parsing the header and validating its structure against the specified device family.
- Parameters:
data (
bytes) – Binary data with XMCD to be verified.family (
FamilyRevision) – Device family revision for validation context.
- Return type:
Verifier- Returns:
Verifier object containing pre-parsed binary data verification results.
- property registers: Registers#
Get configuration block registers with conditional option handling.
Creates a deep copy of the internal registers and conditionally removes the configOption1 register based on the optionSize bitfield value in configOption0. If optionSize is 0, configOption1 is removed from the register set.
- Returns:
Deep copy of registers with conditional configOption1 removal.
- property size: int#
Get the size of XMCD data in bytes.
- Returns:
Size of the exported XMCD data in bytes.
- verify()#
Verify XMCD data integrity and configuration.
Creates a verification report by parsing the XMCD header and validating it against the current configuration parameters including config type, memory type, and data size.
- Return type:
Verifier- Returns:
Verification report containing validation results for XMCD data.
- class spsdk.image.xmcd.xmcd.XMCDHeader(family)#
Bases:
objectExternal Memory Configuration Data Header.
This class manages the header section of XMCD (External Memory Configuration Data) structures, providing configuration and validation for external memory interfaces across NXP MCU families.
- Variables:
TAG – XMCD header identification tag (0x0C).
Initialize the XMCD Header.
Creates a new XMCD header instance with family-specific register configuration for external memory configuration data.
- Parameters:
family (
FamilyRevision) – Target MCU family and revision information.- Raises:
SPSDKError – When register configuration cannot be loaded for the family.
- TAG = 12#
- property config_block_size: int#
Get the size of XMCD configuration data blob.
Calculates the size of the configuration data portion by subtracting the base XMCD structure size from the total XMCD size. Returns 0 if the calculated size would be negative.
- Returns:
Size of the configuration data blob in bytes, or 0 if no config data exists.
- property config_type: ConfigurationBlockType#
Get configuration block type from header register.
Retrieves the configuration block type value from the header register’s configurationBlockType bitfield and converts it to the appropriate enum type.
- Returns:
Configuration block type enum value.
- Raises:
SPSDKError – If the configuration block type value is invalid.
- property mem_type: MemoryType#
Get memory type from XMCD configuration.
Retrieves the memory interface type from the header register and maps it to the corresponding supported memory type enumeration value.
- Raises:
SPSDKValueError – When memory type index is not supported.
- Returns:
Memory type enumeration value.
- parse(data)#
Parse XMCD Header from binary data.
- Parameters:
data (
bytes) – Binary data containing the XMCD header information to be parsed.- Raises:
SPSDKError – If the data cannot be parsed or is invalid.
- Return type:
None
- property size: int#
Get the size of the XMCD header.
- Returns:
Number of registers in the XMCD header.
- property supported_mem_types: list[MemoryType]#
Get list of supported memory types.
Retrieves all memory types that are supported for the current MCU family from the XMCD database configuration.
- Returns:
List of supported memory types for the family.
- verify(mem_type=None, config_type=None, xmcd_size=None)#
Verify XMCD header data against expected values and constraints.
Performs comprehensive validation of XMCD header fields including tag verification, version checking, configuration block size validation, configuration block type verification, and memory interface validation against supported types.
- Parameters:
mem_type (
Optional[MemoryType]) – Expected memory type to validate against, optional validation if None.config_type (
Optional[ConfigurationBlockType]) – Expected configuration block type to validate against, optional validation if None.xmcd_size (
Optional[int]) – Expected XMCD size to validate against, validates size > header size if None.
- Return type:
Verifier- Returns:
Verifier object containing all validation results and status information.
- property xmcd_size: int#
Get the size of configuration block including XMCD header itself.
- Returns:
Size of the configuration block in bytes.
Inline Encryption Engine (IEE)#
SPSDK IEE (In-Line Encryption Engine) support module.
This module provides functionality for handling IEE operations including encryption, decryption, and key management for NXP MCUs with IEE capabilities.
On-the-Fly AES Decryption (OTFAD)#
SPSDK OTFAD (On-the-Fly AES Decryption) implementation.
This module provides functionality for handling OTFAD operations in SPSDK context, enabling secure on-the-fly decryption of encrypted data in NXP MCU applications.
Certification blocks#
SPSDK Certificate Block management and processing utilities.
This module provides comprehensive functionality for handling various types of certificate blocks used in NXP secure boot and authentication processes. It supports multiple certificate block versions and formats including V1, V2.1, Vx, and AHAB certificate blocks with their respective headers and structures.
- class spsdk.image.cert_block.cert_blocks.CertBlock(family)#
Bases:
FeatureBaseClassCertificate Block base class for secure boot authentication.
This class provides a unified interface for managing different versions of certificate blocks used in NXP MCU secure boot processes. It handles certificate validation, root key management, and family-specific implementations across the SPSDK-supported device portfolio.
- Variables:
FEATURE – Database manager feature identifier for certificate blocks.
Initialize certificate block with family revision.
- Parameters:
family (
FamilyRevision) – Family revision specification for the certificate block.
-
FEATURE:
str= 'cert_block'#
- classmethod find_main_cert_index(config)#
Find the index of the main certificate that matches the private key.
Searches through all root certificates in the configuration to find the one whose public key corresponds to the configured signature provider’s private key.
- Parameters:
config (
Config) – Configuration object containing certificate and signature provider settings.- Return type:
Optional[int]- Returns:
Index of the matching certificate, or None if no match is found.
- classmethod get_all_supported_families()#
Get supported families for all certification blocks.
This class method aggregates and returns all supported family revisions from all available certification block types in the SPSDK library.
- Return type:
list[FamilyRevision]- Returns:
List of all supported family revisions across all cert block types.
- classmethod get_cert_block_class(family)#
Get certification block class by family name.
Retrieves the appropriate certification block class that supports the specified chip family from all available certification block classes.
- Parameters:
family (
FamilyRevision) – Chip family to find certification block class for.- Raises:
SPSDKError – No certification block class found for given family.
- Return type:
Type[CertBlock]- Returns:
Certification block class that supports the specified family.
- classmethod get_cert_block_classes()#
Get list of all certificate block classes.
This method returns all subclasses of CertBlock that are currently loaded in the system.
- Return type:
list[Type[CertBlock]]- Returns:
List of all certificate block class types.
- classmethod get_main_cert_index(config)#
Gets main certificate index from configuration.
The method retrieves the main root certificate ID from the configuration and validates it against the found certificate index. If no root certificate ID is specified in the configuration, it attempts to find one automatically.
- Parameters:
config (
Config) – Input standard configuration containing certificate settings.- Return type:
int- Returns:
Certificate index of the main certificate.
- Raises:
SPSDKError – If invalid configuration is provided.
SPSDKError – If correct certificate could not be identified.
SPSDKValueError – If certificate is not of correct type.
- get_root_public_key()#
Get the root public key from the certificate block.
- Raises:
SPSDKNotImplementedError – When called on the base class (this method must be implemented by subclasses).
- Return type:
- classmethod get_validation_schemas_from_cfg(config)#
Get validation schemas based on configuration.
This method validates the provided configuration against basic schemas, extracts the family information, and returns the appropriate validation schemas for the specific certificate block class.
- Parameters:
config (
Config) – Valid configuration object containing family and other settings.- Return type:
list[dict[str,Any]]- Returns:
List of validation schema dictionaries for the certificate block.
- classmethod parse(data, family=Unknown, Revision: latest)#
Parse Certification block from binary file.
- Parameters:
data (
bytes) – Binary data of certification blockfamily (
FamilyRevision) – Chip family
- Raises:
SPSDKNotImplementedError – The method is not implemented in sub class
- Return type:
Self
- property rkth: bytes#
Get Root Key Table Hash.
Returns a 32-byte hash (SHA-256) of SHA-256 hashes of up to four root public keys.
- Returns:
Root Key Table Hash as bytes.
- class spsdk.image.cert_block.cert_blocks.CertBlockAhab(family, ahab_certificate=None, **kwargs)#
Bases:
CertBlockCertificate block implementation using AHAB Certificate format.
This class provides certificate block functionality based on AHAB (Advanced High Assurance Boot) certificates, supporting SRK-based certificate blocks with AHAB v2 48-byte format for compatible chip families.
- Variables:
SUB_FEATURE – Identifier for SRK-based certificate block type.
Initialize AHAB-based certificate block.
Creates a new AHAB certificate block instance either from an existing AHAB certificate or by creating a new one using the provided arguments.
- Parameters:
family (
FamilyRevision) – Chip family and revision information.ahab_certificate (
Optional[AhabCertificate]) – Optional existing AHAB Certificate instance to use.kwargs – Additional keyword arguments for AHAB certificate creation when ahab_certificate is not provided.
-
SUB_FEATURE:
Optional[str] = 'based_on_srk'#
- property ahab_certificate: AhabCertificate#
Get the underlying AHAB certificate.
- Returns:
The AHAB certificate instance associated with this certificate block.
- property expected_size: int#
Get expected size of binary block.
- Returns:
Size of the AHAB certificate in bytes.
- export()#
Export certificate block as bytes.
Updates the internal AHAB certificate fields and exports the complete certificate block data in binary format.
- Return type:
bytes- Returns:
Binary representation of the certificate block.
- get_config(data_path='./')#
Create configuration of Certificate Block from object.
- Parameters:
data_path (
str) – Output folder to store possible files.- Return type:
Config- Returns:
Configuration dictionary.
- get_root_public_key()#
Get the root public key from the certificate block.
Extracts and returns the first public key from the AHAB certificate, which serves as the root public key for certificate validation.
- Raises:
SPSDKError – No public key available in AHAB certificate.
- Return type:
- Returns:
Public key object from the first public key in AHAB certificate.
- classmethod get_supported_families(include_predecessors=False)#
Get supported families for this certificate block.
Returns families that have cert_block configuration with: - sub_features: [based_on_srk] - rot_type: “srk_table_ahab_v2_48_bytes”
- Parameters:
include_predecessors (
bool) – Whether to include predecessor family revisions in the search.- Return type:
list[FamilyRevision]- Returns:
List of supported family revisions that meet the configuration requirements.
- classmethod get_validation_schemas(family)#
Create the list of validation schemas for the specified family.
The method retrieves the appropriate AHAB certificate class for the given family and delegates the schema creation to that class.
- Parameters:
family (
FamilyRevision) – Family revision to get validation schemas for.- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas for the specified family.
- classmethod load_from_config(config)#
Create an instance of CertBlockAhab from configuration.
Loads family revision and AHAB certificate from the provided configuration and constructs a new CertBlockAhab instance.
- Parameters:
config (
Config) – Input standard configuration containing family and certificate data.- Return type:
Self- Returns:
Instance of CertBlockAhab with loaded family and certificate.
- classmethod parse(data, family=Unknown, Revision: latest)#
Parse Certificate block from binary data.
Creates a CertBlockAhab instance by parsing the provided binary data and extracting the AHAB certificate information specific to the given chip family.
- Parameters:
data (
bytes) – Binary data of certification blockfamily (
FamilyRevision) – Chip family revision information
- Return type:
Self- Returns:
CertBlockAhab instance
- property signature_size: int#
Get the total size of signatures in bytes.
Calculates the combined size of both public key signatures (key 0 and key 1) from the AHAB certificate. If a public key is not available or causes an error, its signature size is treated as 0.
- Returns:
Total signature size in bytes from both public keys.
- class spsdk.image.cert_block.cert_blocks.CertBlockHeader(version='1.0', flags=0, build_number=0)#
Bases:
BaseClassCertificate block header for SPSDK image processing.
This class represents the header structure of a certificate block used in secure boot images. It manages certificate block metadata including version information, flags, build numbers, and certificate table properties.
- Variables:
FORMAT – Binary format string for header serialization.
SIZE – Size of the header in bytes.
SIGNATURE – Binary signature identifying certificate blocks.
Initialize certificate block header.
- Parameters:
version (
str) – Version of the certificate in format n.n (e.g., “1.0”).flags (
int) – Flags for the Certificate Header.build_number (
int) – Build number of the certificate.
- Raises:
SPSDKError – When there is invalid version format.
- FORMAT = '<4s2H6I'#
- SIGNATURE = b'cert'#
- SIZE = 32#
- export()#
Export certificate block to binary format.
Converts the certificate block structure into its binary representation using the defined format with signature, version, size, flags, and certificate information.
- Return type:
bytes- Returns:
Certificate block data in binary format.
- classmethod parse(data)#
Parse Certificate Header object from bytes array.
The method validates the input data size and signature, then unpacks the binary data to create a Certificate Header instance with proper version formatting.
- Parameters:
data (
bytes) – Input data as bytes containing the certificate header- Return type:
Self- Returns:
Certificate Header instance
- Raises:
SPSDKError – Unexpected size or signature of data
- class spsdk.image.cert_block.cert_blocks.CertBlockV1(family, version='1.0', flags=0, build_number=0)#
Bases:
CertBlockCertificate block version 1 implementation.
This class represents a certificate block used in SB file 2.1 and MasterBootImage operations with RSA keys. It manages certificate chains, root key hashes, and provides functionality for signature verification and key management.
- Variables:
SUB_FEATURE – Feature identifier for certificate block version 1.
DEFAULT_ALIGNMENT – Default size alignment value in bytes.
Initialize certificate block with specified parameters.
- Parameters:
family (
FamilyRevision) – Chip family and revision information for target device.version (
str) – Certificate version string in format “major.minor” (default “1.0”).flags (
int) – Configuration flags for the Certificate Block Header (default 0).build_number (
int) – Build number identifier for the certificate (default 0).
- DEFAULT_ALIGNMENT = 16#
-
SUB_FEATURE:
Optional[str] = 'based_on_cert1'#
- add_certificate(cert)#
Add certificate to the certificate block.
First call adds root certificate. Additional calls add chain certificates. The root certificate must be self-signed and all chain certificates must be verifiable using their parent certificate’s public key.
- Parameters:
cert (
Union[bytes,Certificate]) – Certificate in DER format (bytes) or Certificate object- Raises:
SPSDKError – If certificate cannot be added due to invalid type, unsupported version, verification failure, or root certificate not self-signed
- Return type:
None
- property alignment: int#
Get alignment of the binary output.
The method returns the alignment value for binary output formatting. By default it uses DEFAULT_ALIGNMENT but can be customized.
- Returns:
Alignment value in bytes.
- property certificates: list[Certificate]#
List of certificates in header.
First certificate is root certificate and followed by optional chain certificates.
- Returns:
List of Certificate objects, with root certificate first followed by chain certificates.
- property expected_size: int#
Get expected size of binary block.
- Returns:
Expected size of the binary block in bytes.
- export()#
Export Certificate Block V1 object to binary format.
Validates the certificate chain structure and exports the complete certificate block including header, certificates, and root key hash table (RKHT). The method ensures proper certificate chain validation and alignment requirements.
- Raises:
SPSDKError – If no certificates are present, root key hash index is missing, certificate chain structure is invalid, or exported data length is incorrect.
- Return type:
bytes- Returns:
Binary representation of the Certificate Block V1.
- get_config(data_path='./')#
Create configuration of Certificate V2 from object.
Generates a configuration dictionary containing certificate file references and metadata. The method extracts certificate data from the current object and saves individual certificates to files in the specified directory.
- Parameters:
data_path (
str) – Output folder path to store certificate files.- Raises:
SPSDKError – When index of used certificate is not defined.
- Return type:
Config- Returns:
Configuration dictionary with certificate file paths and metadata.
- get_root_public_key()#
Get the root public key from the certificate block.
The method extracts the public key from the first certificate in the certificate chain, which represents the root certificate.
- Return type:
- Returns:
Root certificate public key object.
- classmethod get_validation_schemas(family)#
Create the list of validation schemas for certificate blocks.
The method retrieves and configures validation schemas including family-specific schemas, certificate schemas, and output schemas. It updates the family schema with supported families and current family information.
- Parameters:
family (
FamilyRevision) – Target family and revision for schema validation.- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas including family, certificate, root keys, and output schemas.
- property header: CertBlockHeader#
Get the certificate block header.
- Returns:
Certificate block header instance.
- property image_length: int#
Get image length in bytes.
- Returns:
Image length in bytes from the certificate block header.
- classmethod load_from_config(config)#
Creates an instance of CertBlockV1 from configuration.
The method supports loading from binary file or creating from certificate configuration. It processes root certificates, certificate chains, and validates the configuration to build a complete certificate block structure.
- Parameters:
config (
Config) – Input standard configuration containing certificate paths and settings.- Return type:
Self- Returns:
Instance of CertBlockV1 with loaded certificates and configuration.
- Raises:
SPSDKError – Invalid certificates detected, invalid configuration, or missing required root certificate files.
- classmethod parse(data, family=Unknown, Revision: latest)#
Parse CertBlockV1 from binary data.
Parses the binary data to create a CertBlockV1 instance by extracting the header, certificates, and root key hash table from the provided data.
- Parameters:
data (
bytes) – Binary data containing the certificate blockfamily (
FamilyRevision) – The MCU family revision for the certificate block
- Return type:
Self- Returns:
Certificate Block instance
- Raises:
SPSDKError – Length of the data doesn’t match Certificate Block length
- property raw_size: int#
Calculate the aligned size of the certificate block in bytes.
The method computes the total size by adding the certificate block header size, certificate table length, and Root Key Hash Table (RKHT) size, then aligns the result to the specified alignment boundary.
- Returns:
Total aligned size of the certificate block in bytes.
- property rkh: list[bytes]#
Get list of root keys hashes.
Returns SHA-256 hashes of root keys from the root key hash table.
- Returns:
List of root key hashes, each hash as 32 bytes.
- property rkh_index: int | None#
Get the index of Root Key Hash that matches the certificate.
The method searches through the available Root Key Hashes to find a match with the certificate’s root public key hash. Returns None if no match is found or if no certificate is available.
- Returns:
Index of matching Root Key Hash, or None if no match found.
- property rkth: bytes#
Get Root Key Table Hash.
Returns a 32-byte SHA-256 hash of SHA-256 hashes of up to four root public keys from the Root Key Hash Table.
- Returns:
32-byte hash as bytes.
- property rkth_fuses: list[int]#
Get list of RKHT fuses ordered from highest bit to lowest.
The method processes the RKHT (Root Key Table Hash) data by splitting it into 4-byte chunks and converting each chunk to an integer using little-endian byte order. The returned values are formatted for use with blhost tool.
- Returns:
List of RKHT fuse values as integers.
- set_root_key_hash(index, key_hash)#
Set root key hash into RKHT at specified index.
Multiple root public keys are supported to allow for key revocation.
- Parameters:
index (
int) – The index of Root Key Hash in the table.key_hash (
Union[bytes,bytearray,Certificate]) – The Root Key Hash value (32 bytes, SHA-256) or Certificate where the hash can be created from public key.
- Raises:
SPSDKError – When there is invalid index of root key hash in the table.
SPSDKError – When there is invalid length of key hash.
- Return type:
None
- property signature_size: int#
Get the size of the signature in bytes.
Returns the size of the first certificate’s signature, which is used as the reference since the certificate is self-signed.
- Returns:
Size of the signature in bytes.
- verify_data(signature, data)#
Verify signature against signed data using certificate.
The method uses the public key from the last certificate in the chain to verify that the provided signature matches the given data.
- Parameters:
signature (
bytes) – Signature bytes to be verified.data (
bytes) – Original data that has been signed.
- Return type:
bool- Returns:
True if the data signature can be confirmed using the certificate; False otherwise.
- verify_private_key(private_key)#
Verify that given private key matches the public certificate.
The method compares the private key against the public key from the last certificate in the certificate chain to ensure they form a valid key pair.
- Parameters:
private_key (
PrivateKeyRsa) – Private RSA key to be verified against the certificate.- Return type:
bool- Returns:
True if the private key matches the public certificate; False otherwise.
- class spsdk.image.cert_block.cert_blocks.CertBlockV21(family, root_certs=None, ca_flag=False, version='2.1', used_root_cert=0, constraints=0, signature_provider=None, isk_cert=None, user_data=None)#
Bases:
CertBlockCertificate block implementation for version 2.1.
This class manages certificate blocks used in Secure Binary 3.1 and Master Boot Image operations with ECC cryptographic keys. It handles root certificates, ISK certificates, and provides the necessary structure for secure boot chain validation.
- Variables:
SUB_FEATURE – Feature identifier for certificate block v2.1.
MAGIC – Magic bytes identifier for the certificate block header.
FORMAT_VERSION – Version string for this certificate block format.
Initialize Certificate block with specified configuration.
Creates a certificate block with header, root key record, and optionally an ISK certificate based on the provided parameters and CA flag setting.
- Parameters:
family (
FamilyRevision) – Target MCU family and revision information.root_certs (
Union[Sequence[PublicKeyEcc],Sequence[bytes],None]) – Sequence of root certificates as PublicKeyEcc objects or raw bytes.ca_flag (
bool) – Whether this is a Certificate Authority block, defaults to False.version (
str) – Certificate block version string, defaults to “2.1”.used_root_cert (
int) – Index of the root certificate to use, defaults to 0.constraints (
int) – Certificate constraints value, defaults to 0.signature_provider (
Optional[SignatureProvider]) – Provider for cryptographic signatures.isk_cert (
Union[PublicKeyEcc,bytes,None]) – ISK certificate as PublicKeyEcc object or raw bytes.user_data (
Optional[bytes]) – Additional user-defined data to include in ISK certificate.
- FORMAT_VERSION = '2.1'#
- MAGIC = b'chdr'#
-
SUB_FEATURE:
Optional[str] = 'based_on_cert21'#
- calculate()#
Calculate all internal members.
This method triggers the calculation of all internal components within the certificate block, including the root key record and any other dependent structures.
- Return type:
None
- property expected_size: int#
Calculate the expected size of the certificate block in bytes.
The method calculates the total size by summing the header size, root key record size, and ISK certificate size (if present).
- Returns:
Expected size of the binary certificate block in bytes.
- export()#
Export Certificate block as bytes array.
This method serializes the certificate block into a binary format by combining the header, root key record, and optional ISK certificate data. The header’s cert_block_size field is automatically updated to reflect the total size.
- Return type:
bytes- Returns:
Binary representation of the certificate block.
- get_config(data_path='./')#
Create configuration dictionary of the Certification block Image.
The method generates a configuration that includes root certificates, ISK certificate settings, and associated data files. It saves public keys and user data to the specified data path and creates appropriate configuration entries.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary with certificate block settings.
- get_root_public_key()#
Get the root public key from the certificate block.
- Raises:
SPSDKError – If root key record is not available or parsing fails.
- Return type:
- Returns:
Root public key object parsed from the certificate block.
- classmethod get_validation_schemas(family)#
Create the list of validation schemas for certificate blocks.
The method retrieves and configures validation schemas including family-specific schemas, certificate schemas, root keys schemas, and output schemas. It updates the family schema with supported families for the given family revision.
- Parameters:
family (
FamilyRevision) – Family revision to configure validation schemas for.- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas including family, certificate, root keys, and output schemas.
- classmethod load_from_config(config)#
Creates an instance of CertBlockV21 from configuration.
The method supports loading from binary file or creating from configuration parameters. It handles root certificates, ISK certificates, constraints, and signature providers.
- Parameters:
config (
Config) – Input standard configuration containing certificate block settings.- Return type:
Self- Returns:
Instance of CertBlockV21 with calculated certificate block.
- Raises:
SPSDKError – If main root certificate ID doesn’t exist or configuration is invalid.
- classmethod parse(data, family=Unknown, Revision: latest)#
Parse CertBlockV21 from binary data.
The method parses binary data to create a Certificate Block V2.1 instance, including certificate header, root key record, and optional ISK certificate.
- Parameters:
data (
bytes) – Binary data to parsefamily (
FamilyRevision) – The MCU family revision
- Return type:
Self- Returns:
Certificate Block V2.1 instance
- Raises:
SPSDKError – Length of the data doesn’t match Certificate Block length
- property rkth: bytes#
Get Root Key Table Hash.
Returns a 32-byte SHA-256 hash of the SHA-256 hashes of up to four root public keys from the root key record.
- Returns:
32-byte hash as bytes.
- property signature_size: int#
Get the size of the signature in bytes.
The signature size is determined by the public key data length from either the ISK certificate or the root key record, whichever is available.
- Returns:
Size of the signature in bytes.
- validate()#
Validate the settings of certification block class members.
This method performs validation checks on the certification block configuration, including header parsing and ISK certificate signature validation.
- Raises:
SPSDKError – Invalid configuration of certification block class members.
- Return type:
None
- class spsdk.image.cert_block.cert_blocks.CertBlockVx(family, isk_cert, signature_provider=None, self_signed=True)#
Bases:
CertBlockCertificate block implementation for MC56xx family devices.
This class provides certificate block functionality specifically designed for MC56xx microcontrollers, handling ISK (Intermediate Signing Key) certificate management, hash calculation, and binary export operations for secure boot processes.
- Variables:
SUB_FEATURE – Feature identifier for certificate-based implementations.
ISK_CERT_LENGTH – Standard length of ISK certificate in bytes.
ISK_CERT_HASH_LENGTH – Length of ISK certificate hash in bytes.
Initialize Certificate block with ISK certificate and signature provider.
Creates a new certificate block instance with the specified family revision, ISK certificate, and optional signature provider for certificate operations.
- Parameters:
family (
FamilyRevision) – Target MCU family and revision information.isk_cert (
Union[PublicKeyEcc,bytes]) – ISK certificate as ECC public key or raw bytes.signature_provider (
Optional[SignatureProvider]) – Optional provider for certificate signing operations.self_signed (
bool) – Whether the certificate should be self-signed.
- ISK_CERT_HASH_LENGTH = 16#
- ISK_CERT_LENGTH = 136#
-
SUB_FEATURE:
Optional[str] = 'based_on_certx'#
- property cert_hash: bytes#
Calculate certificate hash from ISK certificate data.
The method extracts the ISK certificate data and computes a hash, returning only the first 127 bytes of the calculated hash value.
- Returns:
First 127 bytes of the ISK certificate hash.
- property expected_size: int#
Get expected size of binary block.
- Returns:
Expected size of the ISK certificate in bytes.
- export()#
Export Certificate block as bytes array.
Creates ISK signature using the configured signature provider and exports the ISK certificate data.
- Return type:
bytes- Returns:
Certificate block data as bytes.
- get_config(data_path='./')#
Create configuration of the Certification block Image.
- Parameters:
data_path (
str) – Path to directory containing data files for configuration.- Raises:
SPSDKNotImplementedError – Parsing of Cert Block Vx is not supported.
- Return type:
Config
- get_otp_script()#
Generate OTP programming script for writing certificate hash to fuses.
The method creates a blhost script that programs the ISK certificate hash into OTP fuses starting from index 12. The hash is split into 4-byte chunks with proper endianness conversion for fuse programming.
- Return type:
str- Returns:
Blhost script content as string for OTP fuse programming.
- get_tbs_data()#
Get To-Be-Signed data from the ISK certificate.
This method retrieves the To-Be-Signed (TBS) portion of the ISK (Intermediate Signing Key) certificate, which contains the certificate data that needs to be signed.
- Return type:
bytes- Returns:
The TBS data as bytes from the ISK certificate.
- classmethod get_validation_schemas(family)#
Create the list of validation schemas for certificate blocks.
The method retrieves and configures validation schemas including family-specific schema, certificate schema, and certificate block output schema. It updates the family schema with supported families for the given family revision.
- Parameters:
family (
FamilyRevision) – Family revision to configure validation schemas for.- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas including family, certificate, and output schemas.
- classmethod load_from_config(config)#
Create an instance of CertBlockVx from configuration.
The method supports loading from binary file or creating from configuration parameters. It handles ISK certificates, signature providers, and family-specific settings.
- Parameters:
config (
Config) – Input standard configuration containing certificate block settings.- Return type:
Self- Returns:
CertBlockVx instance configured according to the provided configuration.
- Raises:
SPSDKError – If found gap in certificates from config file or invalid configuration.
- classmethod parse(data, family=Unknown, Revision: latest)#
Parse CertBlockVx from binary file.
The method creates a Certificate Block instance by parsing the ISK certificate from the provided binary data and extracting the public key and signature information.
- Parameters:
data (
bytes) – Binary data containing the certificate block information.family (
FamilyRevision) – The MCU family revision for the certificate block.
- Return type:
Self- Returns:
Certificate Block instance with parsed ISK certificate data.
- Raises:
SPSDKError – Length of the data doesn’t match Certificate Block length.
- validate()#
Validate the settings of certification block class members.
This method checks if the ISK certificate configuration is valid, specifically verifying that when an ISK certificate exists without a signature, a proper signature provider must be available.
- Raises:
SPSDKError – Invalid ISK certificate configuration when certificate exists without signature but no valid signature provider is set.
- Return type:
None
- class spsdk.image.cert_block.cert_blocks.CertificateBlockHeader(format_version='2.1')#
Bases:
BaseClassCertificate block header for SPSDK image processing.
This class represents the header structure of certificate blocks used in secure boot images. It handles the binary format, version information, and size management for certificate block headers in NXP MCU secure provisioning.
- Variables:
FORMAT – Binary format string for header structure.
SIZE – Size of the header in bytes.
MAGIC – Magic bytes identifier for certificate block headers.
Initialize Certificate block header.
Creates a new certificate block header with specified format version. The header manages certificate block metadata including size and version information.
- Parameters:
format_version (
str) – Certificate block format version in “major.minor” format, defaults to “2.1”
- FORMAT = '<4s2HL'#
- MAGIC = b'chdr'#
- SIZE = 12#
- export()#
Export Certificate block header as bytes array.
Converts the certificate block header into a binary format by packing the magic number, format version components, and block size according to the defined FORMAT structure.
- Return type:
bytes- Returns:
Binary representation of the certificate block header.
- classmethod parse(data)#
Parse Certificate block header from bytes array.
- Parameters:
data (
bytes) – Input data as bytes array to be parsed.- Raises:
SPSDKError – Raised when SIZE is bigger than length of the data.
SPSDKError – Raised when magic number doesn’t match expected MAGIC value.
- Return type:
Self- Returns:
CertificateBlockHeader instance with parsed data.
- class spsdk.image.cert_block.cert_blocks.CertificateBlockHeaderV2_2(format_version='2.2')#
Bases:
CertificateBlockHeaderCertificate block header implementation for format version 2.2.
This class extends the base certificate block header to support version 2.2 format which includes additional flags field for enhanced functionality.
- Variables:
FORMAT – Binary format string for packing/unpacking header data.
SIZE – Size of the header in bytes.
Initialize Certificate block header version 2.2.
Creates a new certificate block header with the specified format version and initializes flags to zero.
- Parameters:
format_version (
str) – Format version string in “major.minor” format, defaults to “2.2”.
- FORMAT = '<4s2H2L'#
- SIZE = 16#
- export()#
Export Certificate block header as bytes array.
Serializes the certificate block header into a binary format using the predefined structure with magic number, version information, size, and flags.
- Return type:
bytes- Returns:
Binary representation of the certificate block header.
- classmethod parse(data)#
Parse Certificate block header from bytes array.
- Parameters:
data (
bytes) – Input data as bytes array to parse the certificate block header from.- Raises:
SPSDKError – Raised when SIZE is bigger than length of the data without offset.
SPSDKError – Raised when magic number is not equal to expected MAGIC value.
- Return type:
Self- Returns:
CertificateBlockHeaderV2_2 instance with parsed header data.
- class spsdk.image.cert_block.cert_blocks.IskCertificate(constraints=0, signature_provider=None, isk_cert=None, user_data=None, offset_present=True, family=None)#
Bases:
BaseClassISK Certificate representation for secure boot operations.
This class manages the creation, validation, and export of ISK (Image Signing Key) certificates used in NXP secure boot processes. It handles certificate constraints, signature operations, user data embedding, and ensures proper alignment and size validation according to device family specifications.
Initialize ISK certificate block.
Creates a new ISK (Intermediate Signing Key) certificate block with the specified parameters and validates user data constraints based on the target family.
- Parameters:
constraints (
int) – Certificate constraints/version value.signature_provider (
Optional[SignatureProvider]) – Signature provider for ISK certificate signing.isk_cert (
Union[PublicKeyEcc,bytes,None]) – ISK certificate as ECC public key or raw bytes.user_data (
Optional[bytes]) – Additional user data to include in the certificate.offset_present (
bool) – Whether offset field is present in the certificate.family (
Optional[FamilyRevision]) – Target MCU family for validation of data constraints.
- Raises:
SPSDKError – If user data exceeds size limit or alignment requirements.
- create_isk_signature(key_record_data, force=False)#
Create ISK signature for the certificate.
The method generates a signature using the provided key record data combined with certificate metadata (offset, constraints, flags) and ISK public key data.
- Parameters:
key_record_data (
bytes) – Binary data of the key record to be signed.force (
bool) – Force signature creation even if signature already exists.
- Raises:
SPSDKError – Signature provider is not specified.
- Return type:
None
- property expected_size: int#
Calculate the expected binary size of the certificate block.
The method computes the total size by summing up all components including signature offset (if present), constraints, flags, ISK public key data, user data, and ISK blob signature. The signature length is determined from either existing signature or signature provider.
- Returns:
Total expected size in bytes of the binary certificate block.
- export()#
Export ISK certificate as bytes array.
Serializes the ISK (Initial Secure Key) certificate into a binary format by packing the certificate components including signature offset, constraints, flags, public key data, user data, and signature.
- Raises:
SPSDKError – If signature is not set or if the exported data size does not match the expected size.
- Return type:
bytes- Returns:
Binary representation of the ISK certificate.
- classmethod parse(data, signature_size)#
Parse ISK certificate from bytes array.
Parses the ISK (Initial Secure Key) certificate data structure including signature offset, constraints, ISK flags, public key, optional user data, and signature components.
- Parameters:
data (
bytes) – Input data as bytes array containing the ISK certificatesignature_size (
int) – The signature size of ISK block in bytes
- Return type:
Self- Returns:
Parsed ISK certificate instance
- Raises:
SPSDKError – Invalid certificate data format or parsing error
- property signature_offset: int#
Calculate the signature offset inside the ISK Certificate.
The method computes the offset by considering the header size (with or without offset field), user data length, and ISK certificate coordinate size if present.
- Returns:
Signature offset in bytes from the beginning of the certificate.
- class spsdk.image.cert_block.cert_blocks.IskCertificateLite(pub_key, constraints=1)#
Bases:
BaseClassISK Certificate Lite for secure boot operations.
This class represents a lightweight version of an ISK (Image Signing Key) certificate used in NXP secure boot processes. It manages ISK public key data, constraints, and digital signatures for certificate validation and export operations.
- Variables:
MAGIC – Certificate magic number identifier (0x4D43).
VERSION – Certificate format version.
ISK_PUB_KEY_LENGTH – Expected length of ISK public key data in bytes.
ISK_SIGNATURE_SIZE – Expected size of ISK signature in bytes.
Constructor for ISK certificate.
- Parameters:
pub_key (
Union[PublicKeyEcc,bytes]) – ISK public key, either PublicKeyEcc object or raw bytesconstraints (
int) – Certificate constraints (1 = self signed, 0 = NXP signed)
- HEADER_FORMAT = '<HHI'#
- ISK_PUB_KEY_LENGTH = 64#
- ISK_SIGNATURE_SIZE = 64#
- MAGIC = 19779#
- SIGNATURE_OFFSET = 72#
- VERSION = 1#
- create_isk_signature(signature_provider, force=False)#
Create ISK (Issuer Signing Key) signature for the certificate.
This method generates a digital signature for the certificate using the provided signature provider. If a signature already exists, it will only be replaced when force parameter is set to True.
- Parameters:
signature_provider (
Optional[SignatureProvider]) – Provider used to generate the digital signatureforce (
bool) – Force regeneration of signature even if one already exists
- Raises:
SPSDKError – Signature provider is not specified
- Return type:
None
- property expected_size: int#
Get the expected size of the binary certificate block.
Calculates the total size including magic number, version, constraints, ISK public key coordinates, and ISK blob signature.
- Returns:
Expected size in bytes of the binary certificate block.
- export()#
Export ISK certificate as bytes array.
Serializes the ISK (Initial Secure Key) certificate into a binary format by combining the TBS (To Be Signed) data with the signature.
- Raises:
SPSDKError – Signature is not set or data size does not match expected size.
- Return type:
bytes- Returns:
Binary representation of the ISK certificate.
- get_tbs_data()#
Get To-Be-Signed data for certificate block.
Constructs the data that needs to be signed by packing the header information (magic, version, constraints) and appending the ISK public key data. Validates that the public key length and total data length match expected values.
- Raises:
SPSDKError – Invalid public key length or invalid TBS data length.
- Return type:
bytes- Returns:
Packed binary data ready for signing.
- classmethod parse(data)#
Parse ISK certificate from bytes array.
This method deserializes an ISK (Initial Secure Key) certificate from a binary data format, extracting the constraints, public key, and signature components.
- Parameters:
data (
bytes) – Input data as bytes array containing the serialized ISK certificate.- Return type:
Self- Returns:
Parsed ISK certificate instance.
- class spsdk.image.cert_block.cert_blocks.RootKeyRecord(ca_flag, root_certs=None, used_root_cert=0)#
Bases:
BaseClassRoot Key Record for certificate block operations.
This class manages root key records used in SPSDK certificate blocks, handling root certificates, public keys, and associated metadata for secure boot operations. It supports ECC public keys (P-256/P-384) and manages certificate authority flags, root key hash tables, and certificate selection.
Initialize Root Key Record for certificate block.
Creates a new Root Key Record instance with specified CA flag, root certificates, and the index of the root certificate to be used for ISK/image signature verification.
- Parameters:
ca_flag (
bool) – Certificate Authority flag indicating if this is a CA certificate.root_certs (
Union[Sequence[PublicKeyEcc],Sequence[bytes],None]) – Sequence of root certificates as PublicKeyEcc objects or raw bytes, defaults to None.used_root_cert (
int) – Index of the root certificate to use (0-3), defaults to 0.
- calculate()#
Calculate all internal members of the certificate block.
This method processes root certificates, calculates flags, creates RKHT (Root Key Hash Table), validates hash algorithms, and generates the root public key.
- Raises:
SPSDKError – The RKHT certificates inputs are missing or hash algorithm mismatch.
- Return type:
None
- property expected_size: int#
Get expected binary block size.
Calculates the total size of the certificate block including flags (4 bytes), root key hash table export data, and root public key data.
- Returns:
Expected size in bytes of the binary certificate block.
- export()#
Export Root key record as bytes array.
Serializes the root key record into a binary format including flags, root key hash table, and root public key data.
- Raises:
SPSDKError – Invalid length of exported data.
- Return type:
bytes- Returns:
Binary representation of the root key record.
- static get_hash_algorithm(flags)#
Get CTRK table hash algorithm from flags.
Extracts the hash algorithm type from the lower 4 bits of the Root Key Record flags.
- Parameters:
flags (
int) – Root Key Record flags containing hash algorithm information.- Raises:
KeyError – If the flags contain an unsupported hash algorithm value.
- Return type:
- Returns:
Hash algorithm enumeration value (SHA256 or SHA384).
- property number_of_certificates: int#
Get number of included certificates.
This method extracts the certificate count from the flags field by masking the upper 4 bits and shifting them to get the actual count value.
- Returns:
Number of certificates included in the certificate block.
- classmethod parse(data)#
Parse Root key record from bytes array.
- Parameters:
data (
bytes) – Input data as bytes array- Return type:
Self- Returns:
Root key record object
- spsdk.image.cert_block.cert_blocks.convert_to_ecc_key(key)#
Convert key into ECC key instance.
Converts various key formats (bytes or existing ECC key) into a standardized PublicKeyEcc instance for consistent handling within the certificate block.
- Parameters:
key (
Union[PublicKeyEcc,bytes]) – Input key data as either existing ECC key instance or raw bytes.- Raises:
SPSDKError – When the provided key is not an ECC key type.
- Return type:
- Returns:
Standardized ECC public key instance.
- spsdk.image.cert_block.cert_blocks.find_root_certificates(config)#
Find all root certificates in configuration.
Searches for root certificate file paths in the configuration dictionary by looking for keys matching the pattern ‘rootCertificateXFile’ where X is 0-3. Validates that there are no gaps in the certificate numbering sequence.
- Parameters:
config (
dict[str,Any]) – Configuration dictionary containing certificate file paths.- Raises:
SPSDKError – If there are gaps in rootCertificateXFile definition sequence.
- Return type:
list[str]- Returns:
List of root certificate file paths found in configuration.
- spsdk.image.cert_block.cert_blocks.get_keys_or_rotkh_from_certblock_config(rot, family)#
Get keys or ROTKH value from ROT config.
ROT config might be cert block config or MBI config. There are four cases how cert block might be configured: 1. MBI with certBlock property pointing to YAML file 2. MBI with certBlock property pointing to BIN file 3. YAML configuration of cert block 4. Binary cert block
- Parameters:
rot (
Optional[str]) – Path to ROT configuration (MBI or cert block) or path to binary cert block.family (
Optional[FamilyRevision]) – MCU family.
- Raises:
SPSDKError – In case the ROTKH or keys cannot be parsed.
- Return type:
tuple[Optional[Iterable[str]],Optional[bytes]]- Returns:
Tuple containing root of trust (list of paths to keys) or ROTKH in case of binary cert block.
Certification blocks - Root Keys Hash Table (RKHT)#
SPSDK Root Key Hash Table (RKHT) implementation.
This module provides functionality for creating, parsing, and managing Root Key Hash Tables used in secure boot processes. It supports multiple RKHT versions including RKHTv1 and RKHTv21 with their specific formats and validation requirements.
- class spsdk.image.cert_block.rkht.RKHT(rkh_list)#
Bases:
objectRoot Key Hash Table for secure boot certificate blocks.
This class manages a collection of root key hashes used in secure boot operations. It provides functionality to create hash tables from various key formats including public keys, private keys, and certificates, and calculates the root key table hash for certificate block validation.
Initialize Root Key Hash Table.
Creates a new Root Key Hash Table instance with the provided list of root key hashes. The table supports a maximum of 4 root key hashes.
- Parameters:
rkh_list (
list[bytes]) – List of root key hashes as bytes objects- Raises:
SPSDKError – When more than 4 root key hashes are provided
- static convert_key(key, password=None, search_paths=None)#
Convert various key formats into a PublicKey object.
Accepts multiple input formats including Certificate, PrivateKey, PublicKey objects, file paths as strings, or raw key data as bytes/bytearray and converts them to a standardized PublicKey object.
- Parameters:
key (
Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]) – Public key in Certificate/Private key, Public key as a path to file, loaded bytes or supported class.password (
Optional[str]) – Optional password to open secured private keys, defaults to None.search_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None.
- Raises:
SPSDKError – Invalid key type.
- Return type:
- Returns:
Public Key object.
- classmethod from_keys(keys, password=None, search_paths=None)#
Create RKHT from list of keys.
The method converts various key formats to public keys, validates that all keys are of the same type and use the same hash algorithm, then creates RKHT from their hashes.
- Parameters:
keys (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – List of public keys/certificates/private keys/bytes to processpassword (
Optional[str]) – Optional password to open secured private keys, defaults to Nonesearch_paths (
Optional[list[str]]) – List of paths where to search for the file, defaults to None
- Raises:
SPSDKError – If keys are not of same type or don’t use same hash algorithm
- Return type:
Self- Returns:
New RKHT instance created from the provided keys
- static get_class(family)#
Get RKHT class for given family.
Retrieves the appropriate RKHT (Root Key Hash Table) class implementation based on the specified family revision by looking up the certificate block type in the database.
- Parameters:
family (
FamilyRevision) – The family revision to get RKHT class for.- Return type:
Type[RKHT]- Returns:
RKHT class corresponding to the given family.
- Raises:
SPSDKError – When the family doesn’t support RKHT or has invalid certificate block configuration.
- property hash_algorithm: EnumHashAlgorithm#
Get the hash algorithm used for root key hashes.
Determines the hash algorithm based on the size of the root key hashes in the RKH list.
- Raises:
SPSDKError – When no root key hashes are available to determine algorithm.
- Returns:
Hash algorithm enumeration value.
- property hash_algorithm_size: int#
Get the hash algorithm size in bits.
The method determines the hash algorithm size based on the length of the first Root Key Hash (RKH) in the list. The size is calculated by multiplying the byte length by 8 to get the bit size.
- Raises:
SPSDKError – When no public keys are provided in the RKH list.
- Returns:
Hash algorithm size in bits.
- abstract rkth()#
Root Key Table Hash.
Computes and returns the hash of all public key hashes in the root key table.
- Return type:
bytes- Returns:
Hash of hashes of public keys as bytes.
- class spsdk.image.cert_block.rkht.RKHTv1(rkh_list)#
Bases:
RKHTRoot Key Hash Table implementation for certificate block version 1.
This class manages a table of root key hashes used in certificate block v1 format, providing functionality to store, validate, and export SHA256 hashes of root keys for secure boot verification.
- Variables:
RKHT_SIZE – Number of root key hash entries in the table (4).
RKH_SIZE – Size of each root key hash in bytes (32).
Initialize Root Key Hash Table with provided key hashes.
Validates that all provided root key hashes have the correct size before creating the table.
- Parameters:
rkh_list (
list[bytes]) – List of root key hash bytes, each must be RKH_SIZE length- Raises:
SPSDKError – Invalid key hash size detected
- RKHT_SIZE = 4#
- RKH_SIZE = 32#
- export()#
Export RKHT as bytes.
Converts the Root Key Hash Table (RKHT) to its binary representation by concatenating all root key hashes. Missing entries are filled with zero bytes to maintain the expected table size.
- Raises:
SPSDKError – Invalid length of exported data.
- Return type:
bytes- Returns:
Binary representation of the RKHT table.
- property hash_algorithm: EnumHashAlgorithm#
Get the hash algorithm used for certificate block validation.
- Returns:
The SHA256 hash algorithm enumeration value.
- classmethod parse(rkht)#
Parse Root Key Hash Table into RKHTv1 object.
- Parameters:
rkht (
bytes) – Valid RKHT table as bytes.- Return type:
Self- Returns:
RKHTv1 object with parsed key hashes.
- rkth()#
Root Key Table Hash.
Computes the hash of the exported root key table using the configured hash algorithm.
- Return type:
bytes- Returns:
Hash of the exported root key table data.
- set_rkh(index, rkh)#
Set Root Key Hash at specified index in the hash table.
The method fills gaps with zero-filled hashes if keys are not set consecutively. Validates index bounds and hash size consistency.
- Parameters:
index (
int) – Index in the hash table (0-3).rkh (
bytes) – Root Key Hash bytes to be set.
- Raises:
SPSDKError – If index is greater than 3, hash size doesn’t match existing hashes, or total number of hashes exceeds 4.
- Return type:
None
- class spsdk.image.cert_block.rkht.RKHTv21(rkh_list)#
Bases:
RKHTRoot Key Hash Table implementation for certificate block version 2.1.
This class provides specialized handling of root key hash tables used in certificate block v2.1, including parsing, exporting, and hash computation functionality for cryptographic key validation.
Initialize Root Key Hash Table.
Creates a new Root Key Hash Table instance with the provided list of root key hashes. The table supports a maximum of 4 root key hashes.
- Parameters:
rkh_list (
list[bytes]) – List of root key hashes as bytes objects- Raises:
SPSDKError – When more than 4 root key hashes are provided
- export()#
Export RKHT (Root Key Hash Table) as bytes.
Concatenates all root key hashes from the RKH list into a single byte array for serialization purposes.
- Return type:
bytes- Returns:
Concatenated root key hashes as bytes, empty if RKH list has one or fewer items.
- classmethod parse(rkht, hash_algorithm)#
Parse Root Key Hash Table into RKHTv21 object.
The method validates the RKHT table length against the specified hash algorithm and creates a list of root key hashes by splitting the input data.
- Parameters:
rkht (
bytes) – Valid RKHT table as bytes.hash_algorithm (
EnumHashAlgorithm) – Hash algorithm to be used for validation.
- Raises:
SPSDKError – If RKHT table length doesn’t match the hash algorithm.
- Return type:
Self- Returns:
RKHTv21 object containing parsed root key hashes.
- rkth()#
Get Root Key Table Hash.
Computes the hash of the root key table. If only one root key hash exists, returns that hash directly. For multiple root key hashes, computes and returns the hash of the entire exported root key table.
- Return type:
bytes- Returns:
Root Key Table Hash as bytes, or empty bytes if no records exist.
Certification blocks - Root Of Trust (RoT)#
SPSDK Root of Trust (RoT) hash calculation and certificate block management.
This module provides functionality for calculating RoT hashes and managing certificate blocks across different NXP MCU families. It supports various RoT implementations including HAB and AHAB certificate blocks with different versions and SRK table formats.
- class spsdk.image.cert_block.rot.Rot(family, keys_or_certs, password=None, search_paths=None, hash_algorithm=None)#
Bases:
objectRoot of Trust abstraction for certificate block operations.
This class provides a unified interface for Root of Trust hash calculation and export operations across multiple NXP device families. It automatically selects the appropriate RoT implementation based on the target device family and manages the underlying RoT object lifecycle.
Initialize Root of Trust object.
Creates a Root of Trust instance using the appropriate class based on the specified family revision and provided cryptographic materials.
- Parameters:
family (
FamilyRevision) – Target MCU family and revision specification.keys_or_certs (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – Sequence of cryptographic materials (file paths, raw data, or cryptographic objects) to be used for Root of Trust.password (
Optional[str]) – Optional password for encrypted private keys.search_paths (
Optional[list[str]]) – Optional list of directories to search for key/certificate files.
- calculate_hash()#
Calculate RoT hash.
- Return type:
bytes- Returns:
Hash of the Root of Trust object as bytes.
- export()#
Export RoT (Root of Trust) data.
- Return type:
bytes- Returns:
Exported RoT data as bytes.
- classmethod get_rot_class(family)#
Get RoT class for the specified family.
Retrieves the appropriate Root of Trust (RoT) class based on the family revision by querying the database for the RoT type configuration.
- Parameters:
family (
FamilyRevision) – Family revision to get RoT class for.- Return type:
Type[RotBase]- Returns:
RoT class type for the specified family.
- classmethod get_supported_families()#
Get all supported families for certificate block.
- Return type:
list[FamilyRevision]- Returns:
List of supported family revisions for certificate block operations.
- class spsdk.image.cert_block.rot.RotBase(keys_or_certs, password=None, search_paths=None, hash_algorithm=None)#
Bases:
objectRoot of Trust base class for certificate block operations.
This abstract base class provides a foundation for implementing different types of Root of Trust (RoT) mechanisms used in secure boot and certificate validation. It manages cryptographic keys and certificates, and provides a registry system for different RoT implementations.
- Variables:
rot_type – Identifier for the specific RoT implementation type.
_registry – Registry mapping RoT type strings to their implementation classes.
Initialize Root of Trust (RoT) with cryptographic keys or certificates.
The RoT manages a collection of cryptographic materials that can be provided as file paths, raw data, or cryptographic objects for certificate block creation.
- Parameters:
keys_or_certs (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – Collection of keys or certificates as file paths, raw data, or cryptographic objects (PublicKey, PrivateKey, Certificate).password (
Optional[str]) – Optional password for encrypted key files.search_paths (
Optional[list[str]]) – Optional list of directories to search for key/certificate files.
- abstract calculate_hash()#
Calculate RoT hash.
Computes the hash value for the Root of Trust (RoT) data structure using the configured hash algorithm.
- Return type:
bytes- Returns:
Hash bytes of the RoT data.
- abstract export()#
Export the RoT table as binary data.
Serializes the Root of Trust (RoT) table into its binary representation for use in secure boot processes.
- Return type:
bytes- Returns:
Binary representation of the RoT table.
- classmethod get_rot_class(rot_type)#
Get RoT implementation by type.
Retrieves the RoT (Root of Trust) class implementation based on the specified type from the internal registry.
- Parameters:
rot_type (
str) – The type identifier of the RoT implementation to retrieve.- Raises:
SPSDKError – When the specified RoT type does not exist in the registry.
- Return type:
Type[RotBase]- Returns:
The RoT class implementation corresponding to the specified type.
- classmethod register(rot_class)#
Register a RoT implementation class.
Registers a Root of Trust (RoT) implementation class in the internal registry for later retrieval and instantiation based on RoT type.
-
rot_type:
Optional[str] = None#
- supports_custom_hash_algorithm = False#
- class spsdk.image.cert_block.rot.RotCertBlockv1(keys_or_certs, password=None, search_paths=None, hash_algorithm=None)#
Bases:
RotBaseRoot of Trust implementation for certificate block version 1.
This class provides Root of Trust functionality specifically for certificate block version 1 format, managing cryptographic keys and certificates used in secure boot operations. It handles RKHT (Root Key Hash Table) generation and RoT hash calculation for NXP MCU secure provisioning.
- Variables:
rot_type – Identifier for certificate block v1 RoT type.
Initialize RoT certificate block version 1.
Creates a new RoT (Root of Trust) certificate block v1 instance with the provided keys or certificates and generates the corresponding RKHT (Root Key Hash Table) v1.
- Parameters:
keys_or_certs (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – Sequence of keys or certificates as file paths, raw data, or objects.password (
Optional[str]) – Optional password for encrypted private keys.search_paths (
Optional[list[str]]) – Optional list of directories to search for key/certificate files.
- Raises:
SPSDKError – If RKHT creation fails or invalid keys/certificates provided.
- calculate_hash()#
Calculate RoT hash.
Computes the hash value for the Root of Trust using the internal RKHT (Root Key Hash Table).
- Return type:
bytes- Returns:
Hash bytes of the Root of Trust.
- export()#
Export the Root of Trust (RoT) data as bytes.
- Return type:
bytes- Returns:
Binary representation of the RoT hash table data.
- classmethod parse(data)#
Parse RoT from binary data.
- Return type:
-
rot_type:
Optional[str] = 'cert_block_1'#
- class spsdk.image.cert_block.rot.RotCertBlockv21(keys_or_certs, password=None, search_paths=None, hash_algorithm=None)#
Bases:
RotBaseRoot of Trust implementation for certificate block version 2.1.
This class provides Root of Trust functionality specifically designed for certificate block version 2.1, managing cryptographic keys and certificates used in secure boot processes. It handles RKHT (Root Key Hash Table) generation and RoT hash calculations for NXP MCU secure provisioning.
- Variables:
rot_type – Identifier for certificate block v21 RoT type.
Initialize RoT certificate block v21.
Creates a new instance of the RoT (Root of Trust) certificate block version 21 with the provided keys or certificates and generates the corresponding RKHT.
- Parameters:
keys_or_certs (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – Sequence of keys or certificates as file paths, raw data, or cryptographic objects (PublicKey, PrivateKey, Certificate).password (
Optional[str]) – Optional password for encrypted private keys.search_paths (
Optional[list[str]]) – Optional list of additional paths to search for key/cert files.
- Raises:
SPSDKError – If RKHT creation fails or invalid keys/certificates provided.
- calculate_hash()#
Calculate RoT hash.
- Return type:
bytes
- export()#
Export Root of Trust (RoT) data to binary format.
- Return type:
bytes- Returns:
Binary representation of the RoT data structure.
- classmethod parse(data)#
Parse RoT from binary data.
- Return type:
-
rot_type:
Optional[str] = 'cert_block_21'#
- class spsdk.image.cert_block.rot.RotSrkTableAhab(keys_or_certs, password=None, search_paths=None, hash_algorithm=None)#
Bases:
RotBaseRoot of Trust implementation for AHAB SRK Table operations.
This class manages the creation and validation of Super Root Key (SRK) tables specifically for AHAB (Advanced High Assurance Boot) secure boot operations. It handles key conversion, SRK record creation, and provides hash calculation and export functionality for the root of trust.
- Variables:
rot_type – Identifier for AHAB SRK table root of trust type.
Initialize AHAB SRK table with provided keys or certificates.
Creates an AHAB SRK (Super Root Key) table from the provided sequence of keys or certificates. The keys are converted to the appropriate format and used to create SRK records. The table is then validated for errors.
- Parameters:
keys_or_certs (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – Sequence of keys or certificates in various formats (file paths, raw data, or cryptographic objects).password (
Optional[str]) – Optional password for encrypted keys.search_paths (
Optional[list[str]]) – Optional list of paths to search for key files.
- Raises:
SPSDKError – If the SRK table validation fails.
- calculate_hash()#
Calculate RoT hash.
Computes the hash of the Root of Trust (RoT) by delegating to the SRK (Super Root Key) hash calculation method.
- Return type:
bytes- Returns:
The computed RoT hash as bytes.
- export()#
Export Root of Trust (RoT) data.
- Return type:
bytes- Returns:
Exported RoT data as bytes.
- classmethod parse(data)#
Parse RoT from binary data.
- Return type:
-
rot_type:
Optional[str] = 'srk_table_ahab'#
- supports_custom_hash_algorithm = True#
- class spsdk.image.cert_block.rot.RotSrkTableAhabV2(keys_or_certs, password=None, search_paths=None, hash_algorithm=None)#
Bases:
RotBaseSPSDK Root of Trust implementation for AHAB SRK Table version 2.
This class manages the creation and validation of Root of Trust structures specifically for AHAB (Advanced High Assurance Boot) SRK (Super Root Key) Table version 2. It handles key processing, hash calculation, and export functionality for secure boot operations.
- Variables:
rot_type – Identifier for this Root of Trust type.
Initialize AHAB SRK table with provided keys or certificates.
Creates an AHAB SRK (Super Root Key) table from a sequence of keys or certificates, processes them into SRK records, and validates the resulting table structure.
- Parameters:
keys_or_certs (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – Sequence of keys or certificates in various formats (file paths, raw data, or key/certificate objects) to be included in the SRK table.password (
Optional[str]) – Optional password for encrypted key files.search_paths (
Optional[list[str]]) – Optional list of directory paths to search for key/certificate files.
- Raises:
SPSDKError – If the created SRK table fails validation.
- calculate_hash()#
Calculate RoT hash.
Computes the hash of the Root of Trust (RoT) by delegating to the SRK (Super Root Key) hash calculation method.
- Return type:
bytes- Returns:
The computed RoT hash as bytes.
- export()#
Export Root of Trust (RoT) data.
- Return type:
bytes- Returns:
Exported RoT data as bytes.
- classmethod parse(data)#
Parse RoT from binary data for AHAB SRK Table version 2.
- Return type:
-
rot_type:
Optional[str] = 'srk_table_ahab_v2'#
- supports_custom_hash_algorithm = True#
- class spsdk.image.cert_block.rot.RotSrkTableAhabV2_48Bytes(keys_or_certs, password=None, search_paths=None, hash_algorithm=None)#
Bases:
RotSrkTableAhabV2AHAB Root of Trust SRK Table with 48-byte hash truncation.
This class extends the standard AHAB v2 SRK table implementation to provide a variant that truncates the calculated hash to 48 bytes instead of the full hash length, meeting specific hardware or protocol requirements.
- Variables:
rot_type – Identifier for this RoT variant type.
Initialize AHAB SRK table with provided keys or certificates.
Creates an AHAB SRK (Super Root Key) table from a sequence of keys or certificates, processes them into SRK records, and validates the resulting table structure.
- Parameters:
keys_or_certs (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – Sequence of keys or certificates in various formats (file paths, raw data, or key/certificate objects) to be included in the SRK table.password (
Optional[str]) – Optional password for encrypted key files.search_paths (
Optional[list[str]]) – Optional list of directory paths to search for key/certificate files.
- Raises:
SPSDKError – If the created SRK table fails validation.
- calculate_hash()#
Calculate RoT hash.
Computes the hash value for the Root of Trust (RoT) by calling the parent class hash calculation method and truncating the result to 48 bytes.
- Return type:
bytes- Returns:
First 48 bytes of the calculated hash.
-
rot_type:
Optional[str] = 'srk_table_ahab_v2_48_bytes'#
- class spsdk.image.cert_block.rot.RotSrkTableHab(keys_or_certs, password=None, search_paths=None, hash_algorithm=None)#
Bases:
RotBaseRoot of Trust implementation for HAB (High Assurance Boot) SRK Table.
This class manages the creation and processing of SRK (Super Root Key) tables used in HAB-based secure boot implementations. It handles certificate loading, SRK item creation, and hash calculation for root of trust establishment.
- Variables:
rot_type – Identifier for HAB SRK table root of trust type.
Initialize HAB SRK table with certificates or keys.
Creates a HAB (High Assurance Boot) SRK (Super Root Key) table from the provided certificates or keys. All inputs must be valid certificates for HAB RoT calculation.
- Parameters:
keys_or_certs (
Sequence[Union[str,bytes,bytearray,PublicKey,PrivateKey,Certificate]]) – Sequence of certificates or keys as file paths, raw data, or cryptographic objectspassword (
Optional[str]) – Optional password for encrypted certificate filessearch_paths (
Optional[list[str]]) – Optional list of directories to search for certificate files
- Raises:
SPSDKError – When unable to load certificate or when non-certificate object is provided
- calculate_hash()#
Calculate RoT hash.
The method calculates the Root of Trust hash by exporting the SRK fuses data.
- Return type:
bytes- Returns:
RoT hash as bytes data from SRK fuses export.
- export()#
Export RoT (Root of Trust) data.
- Return type:
bytes- Returns:
Exported RoT data as bytes.
- classmethod parse(data)#
Parse RoT from binary data.
- Return type:
-
rot_type:
Optional[str] = 'srk_table_hab'#
HSE Key Catalog#
Module for HSE key catalog configuration.
This module provides classes for creating, parsing, and manipulating HSE key catalog configurations, including key group entries for both NVM and RAM catalogs.
- class spsdk.image.hse.key_catalog.KeyCatalogCfg(family, nvm_key_groups, ram_key_groups)#
Bases:
FeatureBaseClassHSE Key Catalog Configuration.
Contains the configuration for both NVM and RAM key catalogs, including the key group entries for each catalog.
Initialize the key catalog configuration.
- Parameters:
family (
FamilyRevision) – The family revisionnvm_key_groups (
list[KeyGroupCfgEntry]) – List of key group entries for the NVM catalogram_key_groups (
list[KeyGroupCfgEntry]) – List of key group entries for the RAM catalog
- Raises:
SPSDKValueError – If the key catalog configuration is invalid
- FEATURE: str = 'hse'#
- SUB_FEATURE: Optional[str] = 'key_catalog'#
- export()#
Export the complete key catalog configuration to bytes.
The exported data contains both NVM and RAM key catalogs, with each catalog consisting of key group entries followed by a terminating zero entry.
Format: - NVM key group entries (variable number) - NVM terminating zero entry - RAM key group entries (variable number) - RAM terminating zero entry
- Return type:
bytes- Returns:
Serialized key catalog configuration
- export_nvm_catalog()#
Export the NVM key catalog to bytes.
- Return type:
bytes- Returns:
Serialized NVM key catalog
- export_ram_catalog()#
Export the RAM key catalog to bytes.
- Return type:
bytes- Returns:
Serialized RAM key catalog
- get_config(data_path='./')#
Create configuration of the Feature.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary.
- classmethod get_config_template(family)#
Get feature configuration template.
- Parameters:
family (
FamilyRevision) – The MCU family name.- Return type:
str- Returns:
Template file string representation.
- classmethod get_validation_schemas(family)#
Create the list of validation schemas.
- Parameters:
family (
FamilyRevision) – The CPU/MPU- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas.
- classmethod load_from_config(config)#
Load key catalog configuration from a configuration file.
- Parameters:
config (
Config) – Configuration object- Return type:
Self- Returns:
KeyCatalogCfg instance
- Raises:
SPSDKValueError – If the configuration is invalid
- property nvm_catalog_cfg_size: int#
Get the size of the NVM key catalog configuration in bytes.
The size includes all key group entries plus the terminating zero entry.
- Returns:
Size in bytes
- classmethod parse(data, family=unknown, Revision: latest)#
Parse the raw key catalog data into structured fields.
The input data should contain both NVM and RAM catalogs concatenated together. Each catalog consists of key group entries followed by a terminating zero entry.
- Parameters:
data (
bytes) – Raw key catalog data containing both NVM and RAM catalogsfamily (
FamilyRevision) – Family revision
- Return type:
Self- Returns:
KeyCatalogCfg instance
- Raises:
SPSDKParsingError – If data is missing or has invalid format
- property ram_catalog_cfg_size: int#
Get the size of the RAM key catalog configuration in bytes.
The size includes all key group entries plus the terminating zero entry.
- Returns:
Size in bytes
- class spsdk.image.hse.key_catalog.KeyGroupCfgEntry(mu_mask, group_owner, key_type, num_of_key_slots, max_key_bit_len)#
Bases:
objectHSE Key Group Configuration Entry.
Describes a key group in the HSE key catalog, including key type, size, count, and access rights.
Initialize the key group configuration entry.
- Parameters:
family – The family revision
mu_mask (
MuMask) – MU mask specifying which MUs can access this key groupgroup_owner (
KeyGroupOwner) – Owner of the key group (ANY, CUST, OEM)key_type (
KeyType) – Type of keys in this groupnum_of_key_slots (
int) – Number of key slots in this groupmax_key_bit_len (
HseKeyBits) – Maximum key bit length for keys in this group
- FORMAT = '<BBBBHBB'#
- export()#
Pack the key group configuration entry into bytes.
- Return type:
bytes- Returns:
Packed key group configuration entry bytes
- get_config(data_path='./')#
Create configuration of the Feature.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary.
- classmethod get_size()#
Get the size of the key group configuration entry in bytes.
- Return type:
int- Returns:
Size in bytes
- classmethod load_from_config(config)#
Load key group configuration from a configuration file.
- Parameters:
config (
Config) – Configuration object- Return type:
Self- Returns:
KeyGroupCfgEntry instance
- Raises:
SPSDKValueError – If the configuration is invalid
- classmethod parse(data)#
Parse the raw key group configuration data into structured fields.
- Parameters:
data (
bytes) – Raw key group configuration data as bytesfamily – Family revision
- Return type:
Self- Returns:
HseKeyGroupCfgEntry instance
- Raises:
SPSDKParsingError – If data is missing or has invalid length
- class spsdk.image.hse.key_catalog.KeyGroupOwner(tag, label, description=None)#
Bases:
SpsdkEnumEnumeration of HSE key group owners.
Defines the possible owners for key groups in HSE key catalogs.
- ANY = (0, 'ANY', 'Any owner (CUST or OEM)')#
- CUST = (1, 'CUST', 'Customer owner')#
- OEM = (2, 'OEM', 'OEM owner')#
- class spsdk.image.hse.key_catalog.MuMask(tag, label, description=None)#
Bases:
SpsdkEnumEnumeration of HSE MU (Message Unit) masks.
Defines the possible MU instances that can access a key group.
- ALL = (3, 'ALL', 'Access for all MUs')#
- MU0 = (1, 'MU0', 'Access for MU0')#
- MU1 = (2, 'MU1', 'Access for MU1')#
- NONE = (0, 'NONE', 'No MU access')#
HSE Key Info#
Module for importing and handling HSE key information.
- class spsdk.image.hse.key_info.HseAesBlockModeMask(value)#
Bases:
IntFlagHSE AES Block Mode Mask.
The values represent the cipher mode flags that an AES key can take.
- BLOCK_MODE_ANY = 0#
- BLOCK_MODE_CBC = 4#
- BLOCK_MODE_CCM = 64#
- BLOCK_MODE_CFB = 16#
- BLOCK_MODE_CTR = 2#
- BLOCK_MODE_ECB = 8#
- BLOCK_MODE_GCM = 128#
- BLOCK_MODE_OFB = 32#
- BLOCK_MODE_XTS = 1#
- class spsdk.image.hse.key_info.HseEccCurveId(value)#
Bases:
IntEnumHSE ECC Curve IDs.
- BRAINPOOL_P256R1 = 4#
- BRAINPOOL_P320R1 = 5#
- BRAINPOOL_P384R1 = 6#
- BRAINPOOL_P512R1 = 7#
- CURVE25519 = 10#
- CURVE448 = 12#
- ED25519 = 9#
- ED448 = 11#
- NONE = 0#
- SEC_SECP256R1 = 1#
- SEC_SECP384R1 = 2#
- SEC_SECP521R1 = 3#
- USER_CURVE1 = 101#
- USER_CURVE2 = 102#
- USER_CURVE3 = 103#
- class spsdk.image.hse.key_info.HseKeyFlags(value)#
Bases:
IntFlagHSE Key Flags.
The key flags specifies the operations or restrictions that can be apply to a key.
- ACCESS_DEBUG_PROT = 1024#
- ACCESS_EXPORTABLE = 2048#
- ACCESS_MASK = 3584#
- ACCESS_WRITE_PROT = 512#
- USAGE_AUTHORIZATION = 128#
- USAGE_DECRYPT = 2#
- USAGE_DERIVE = 32#
- USAGE_ENCRYPT = 1#
- USAGE_EXCHANGE = 16#
- USAGE_KEY_PROVISION = 64#
- USAGE_MASK = 12799#
- USAGE_OTFAD_DECRYPT = 8192#
- USAGE_SIGN = 4#
- USAGE_SMR_DECRYPT = 256#
- USAGE_VERIFY = 8#
- USAGE_XTS_TWEAK = 4096#
- class spsdk.image.hse.key_info.HseKeyGroupOwner(value)#
Bases:
IntEnumHSE Key Group owner.
- ANY = 0#
- CUST = 1#
- OEM = 2#
- class spsdk.image.hse.key_info.HseSmrFlags(value)#
Bases:
IntFlagHSE SMR Flags.
A set of flags that define which secure memory region (SMR), shall be verified before the key can be used.
- SMR_0 = 1#
- SMR_1 = 2#
- SMR_10 = 1024#
- SMR_11 = 2048#
- SMR_12 = 4096#
- SMR_13 = 8192#
- SMR_14 = 16384#
- SMR_15 = 32768#
- SMR_16 = 65536#
- SMR_17 = 131072#
- SMR_18 = 262144#
- SMR_19 = 524288#
- SMR_2 = 4#
- SMR_20 = 1048576#
- SMR_21 = 2097152#
- SMR_22 = 4194304#
- SMR_23 = 8388608#
- SMR_24 = 16777216#
- SMR_25 = 33554432#
- SMR_26 = 67108864#
- SMR_27 = 134217728#
- SMR_28 = 268435456#
- SMR_29 = 536870912#
- SMR_3 = 8#
- SMR_30 = 1073741824#
- SMR_31 = 2147483648#
- SMR_4 = 16#
- SMR_5 = 32#
- SMR_6 = 64#
- SMR_7 = 128#
- SMR_8 = 256#
- SMR_9 = 512#
- class spsdk.image.hse.key_info.KeyFormat(tag, label, description=None)#
Bases:
SpsdkEnumHSE Key Format (applicable for ECC keys only).
Defines the format of ECC public keys used in HSE operations.
- COMPRESSED = (2, 'COMPRESSED', 'Standard ECC compressed public key: 0x02/0x03 || X')#
- RAW = (0, 'RAW', 'Raw ECC public key: X || Y')#
- UNCOMPRESSED = (1, 'UNCOMPRESSED', 'Standard ECC uncompressed public key: 0x04 || X || Y')#
- class spsdk.image.hse.key_info.KeyInfo(family, key_flags, key_type, smr_flags, key_bit_len, key_counter=0, specific_data=None)#
Bases:
FeatureBaseClassKey Information structure.
Contains properties of a cryptographic key including flags, bit length, counter, SMR flags, and key type.
Initialize the key information structure.
- Parameters:
key_flags (
HseKeyFlags) – Key flags defining key propertieskey_bit_len (
HseKeyBits) – Length of the key in bitskey_counter (
int) – Key counter for rollback protectionsmr_flags (
HseSmrFlags) – Secure memory region flagskey_type (
KeyType) – Type of the key (HseKeyType or int value)specific_data (
Optional[Dict[str,Any]]) – Specific data for the key type (e.g., ECC curve ID, RSA exponent size)
-
FEATURE:
str= 'hse'#
- FORMAT = '<HHLLBBBB'#
- MAX_KEY_COUNTER_VALUE = 4294967294#
-
SUB_FEATURE:
Optional[str] = 'key_import'#
- export()#
Encode the key info structure to bytes.
- Return type:
bytes- Returns:
Encoded key info as bytes
- get_config(data_path='./')#
Create configuration of the Feature.
- Parameters:
data_path (
str) – Path to store the data files of configuration.- Return type:
Config- Returns:
Configuration dictionary.
- classmethod get_config_template(family)#
Get feature configuration template.
- Parameters:
family (
FamilyRevision) – The MCU family name.peripheral – Peripheral name
interface – Memory interface
- Return type:
str- Returns:
Template file string representation.
- get_key_access_flags()#
Get the key access flags.
- Return type:
List[HseKeyFlags]- Returns:
List of key access flag descriptions
- get_key_usage_flags()#
Get the key usage flags.
- Return type:
List[HseKeyFlags]- Returns:
List of key usage flag descriptions
- classmethod get_size()#
Get the size of the key info structure.
- Return type:
int- Returns:
Size in bytes
- get_smr_flags()#
Get the list of SMR indices that are set in the SMR flags.
- Return type:
List[HseSmrFlags]- Returns:
List of SMR indices (0-31)
- classmethod get_validation_schemas(family)#
Create the list of validation schemas.
- Parameters:
family (
FamilyRevision) – Family revision for which the validation schema should be generated.- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas.
- classmethod load_from_config(config)#
Load key information from a configuration file.
- Parameters:
config_file – Path to the configuration file or file-like object
- Return type:
Self- Returns:
HseKeyInfo instance
- Raises:
SPSDKValueError – If the configuration is invalid
- classmethod parse(data, family=unknown, Revision: latest)#
Parse the raw key info data into structured fields.
- Parameters:
data (
bytes) – Raw key info data as bytes- Raises:
SPSDKParsingError – If data is missing or has invalid length
- Return type:
Self
- property size: int#
Get the size of the key info structure.
- Returns:
Size in bytes
HSE Secure Memory Region#
HSE Secure Memory Region (SMR) module.
This module provides classes and utilities for managing HSE (Hardware Security Engine) Secure Memory Regions, including SMR entries, authentication schemes, and decryption parameters. It supports various authentication methods (ECDSA, EdDSA, RSA, CMAC, HMAC, GMAC) and encryption options for secure boot and runtime verification.
- class spsdk.image.hse.smr.AuthScheme#
Bases:
objectHSE authentication scheme.
This class represents the authentication scheme used to verify data integrity and authenticity. It can be either a MAC-based scheme or a signature-based scheme.
-
AUTH_SCH:
AuthSchemeEnum#
-
HEADER_FORMAT:
str= '<BBBB'#
-
SCH_FORMAT:
str#
- classmethod auth_schemes()#
Get the registry of all registered authentication schemes.
- Return type:
dict[AuthSchemeEnum,Type[AuthScheme]]
- classmethod create(auth_scheme, **kwargs)#
Create an authentication scheme using a MAC algorithm.
- Parameters:
auth_scheme (
AuthSchemeEnum) – The MAC algorithm to usekwargs (
Any) – Additional parameters for the specific MAC scheme
- Return type:
- Returns:
HseAuthScheme instance with MAC scheme
- export()#
Export the signature scheme to binary format.
- Return type:
bytes- Returns:
Binary representation of the signature scheme
- abstract get_config()#
Get configuration dictionary from auth scheme object.
- Return type:
dict[str,Any]- Returns:
Configuration dictionary that can be used to recreate this auth scheme
- classmethod get_scheme_data_size()#
Get the size of the auth scheme structure.
- Return type:
int- Returns:
Size in bytes
- classmethod get_size()#
Get the size of the auth scheme structure including header and scheme data.
- Return type:
int- Returns:
Size in bytes
- property is_mac_scheme: bool#
Check if this is a MAC-based authentication scheme.
- Returns:
True if MAC-based, False if signature-based
- property is_signature_scheme: bool#
Check if this is a signature-based authentication scheme.
- Returns:
True if signature-based, False if MAC-based
- abstract classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
- classmethod parse(data)#
Parse authentication scheme from binary data.
- Parameters:
data (
bytes) – Binary data containing scheme-specific parameters- Return type:
- Returns:
AuthScheme instance
- Raises:
SPSDKParsingError – If data is invalid
- classmethod register(scheme_cls)#
Register a MAC scheme implementation.
- Parameters:
mac_scheme_cls – The MAC scheme class to register
- Return type:
Type[AuthScheme]- Returns:
The registered class (for decorator usage)
- property size: int#
Get the size of the auth scheme structure.
- Returns:
Size in bytes
-
AUTH_SCH:
- class spsdk.image.hse.smr.AuthSchemeEnum(tag, label, description=None)#
Bases:
SpsdkEnumEnumeration of HSE signature schemes.
- CMAC = (17, 'CMAC', 'CMAC (AES)')#
- ECDSA = (128, 'ECDSA', 'ECDSA signature scheme')#
- EDDSA = (129, 'EDDSA', 'EdDSA signature scheme')#
- GMAC = (18, 'GMAC', 'GMAC (AES)')#
- HMAC = (32, 'HMAC', 'HMAC')#
- RSASSA_PKCS1_V15 = (147, 'RSASSA_PKCS1_V15', 'RSASSA_PKCS1_V15 signature scheme')#
- RSASSA_PSS = (148, 'RSASSA_PSS', 'RSASSA_PSS signature scheme')#
- XCBC_MAC = (19, 'XCBC_MAC', 'XCBC MAC (AES128)')#
- class spsdk.image.hse.smr.CipherAlgo(tag, label, description=None)#
Bases:
SpsdkEnumEnumeration of HSE cipher algorithms.
- AES = (16, 'AES', 'AES cipher')#
- NULL = (0, 'NULL', 'NULL cipher')#
- class spsdk.image.hse.smr.CmacScheme(cipher_algo=CipherAlgo(tag=16, label='AES', description='AES cipher'))#
Bases:
MacSchemeCMAC scheme parameters.
-
AUTH_SCH:
AuthSchemeEnum= (17, 'CMAC', 'CMAC (AES)')#
-
SCH_FORMAT:
str= '<BBBB'#
-
cipher_algo:
CipherAlgo= (16, 'AES', 'AES cipher')#
- get_config()#
Get configuration dictionary.
- Return type:
dict[str,Any]
- classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
-
AUTH_SCH:
- class spsdk.image.hse.smr.EcdsaSignScheme(hash_algo)#
Bases:
SignSchemeECDSA signature scheme parameters.
-
AUTH_SCH:
AuthSchemeEnum= (128, 'ECDSA', 'ECDSA signature scheme')#
-
SCH_FORMAT:
str= '<BBBB'#
- get_config()#
Get configuration dictionary.
- Return type:
dict[str,Any]
- classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
-
AUTH_SCH:
- class spsdk.image.hse.smr.EddsaSignScheme(pre_hash_eddsa=False, context_length=0, context_addr=0)#
Bases:
SignSchemeEDDSA signature scheme parameters.
-
AUTH_SCH:
AuthSchemeEnum= (129, 'EDDSA', 'EdDSA signature scheme')#
-
SCH_FORMAT:
str= '<BBBBL'#
-
context_addr:
int= 0#
-
context_length:
int= 0#
- get_config()#
Get configuration dictionary.
- Return type:
dict[str,Any]
- classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
-
pre_hash_eddsa:
bool= False#
-
AUTH_SCH:
- class spsdk.image.hse.smr.GmacScheme(iv_length, iv_addr)#
Bases:
MacSchemeGMAC scheme parameters.
-
AUTH_SCH:
AuthSchemeEnum= (18, 'GMAC', 'GMAC (AES)')#
-
SCH_FORMAT:
str= '<LL'#
- get_config()#
Get configuration dictionary.
- Return type:
dict[str,Any]
-
iv_addr:
int#
-
iv_length:
int#
- classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
-
AUTH_SCH:
- class spsdk.image.hse.smr.HashAlgo(tag, label, description=None)#
Bases:
SpsdkEnumEnumeration of HSE hash algorithms.
- MP = (13, 'MP', 'Miyaguchi-Preneel compression using AES-ECB with 128-bit key size')#
- NULL = (0, 'NULL', 'None')#
- RESERVED1 = (1, 'RESERVED1', 'Reserved (MD5 obsolete)')#
- SHA224 = (3, 'SHA224', 'SHA224 hash')#
- SHA256 = (4, 'SHA256', 'SHA256 hash')#
- SHA384 = (5, 'SHA384', 'SHA384 hash')#
- SHA3_224 = (9, 'SHA3_224', 'SHA3_224 hash')#
- SHA3_256 = (10, 'SHA3_256', 'SHA3_256 hash')#
- SHA3_384 = (11, 'SHA3_384', 'SHA3_384 hash')#
- SHA3_512 = (12, 'SHA3_512', 'SHA3_512 hash')#
- SHA512 = (6, 'SHA512', 'SHA512 hash')#
- SHA512_224 = (7, 'SHA512_224', 'SHA512_224 hash')#
- SHA512_256 = (8, 'SHA512_256', 'SHA512_256 hash')#
- SHA_1 = (2, 'SHA_1', 'SHA1 hash')#
- class spsdk.image.hse.smr.HmacScheme(hash_algo)#
Bases:
MacSchemeHMAC scheme parameters.
-
AUTH_SCH:
AuthSchemeEnum= (32, 'HMAC', 'HMAC')#
-
SCH_FORMAT:
str= '<BBBB'#
- get_config()#
Get configuration dictionary.
- Return type:
dict[str,Any]
- classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
-
AUTH_SCH:
- class spsdk.image.hse.smr.MacScheme#
Bases:
AuthSchemeBase class for HSE MAC schemes.
- class spsdk.image.hse.smr.RsaPkcs1v15Scheme(hash_algo)#
Bases:
SignSchemeRSASSA_PKCS1_V15 signature scheme parameters.
-
AUTH_SCH:
AuthSchemeEnum= (147, 'RSASSA_PKCS1_V15', 'RSASSA_PKCS1_V15 signature scheme')#
-
SCH_FORMAT:
str= '<BBBB'#
- get_config()#
Get configuration dictionary.
- Return type:
dict[str,Any]
- classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
-
AUTH_SCH:
- class spsdk.image.hse.smr.RsaPssSignScheme(hash_algo, salt_length=0)#
Bases:
SignSchemeRSASSA_PSS signature scheme parameters.
-
AUTH_SCH:
AuthSchemeEnum= (148, 'RSASSA_PSS', 'RSASSA_PSS signature scheme')#
-
SCH_FORMAT:
str= '<BBBBL'#
- get_config()#
Get configuration dictionary.
- Return type:
dict[str,Any]
- classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
-
salt_length:
int= 0#
-
AUTH_SCH:
- class spsdk.image.hse.smr.SignScheme#
Bases:
AuthSchemeBase class for HSE signature schemes.
- class spsdk.image.hse.smr.SmrConfigFlags(tag, label, description=None)#
Bases:
SpsdkEnumEnumeration of HSE SMR configuration flags.
Defines the available configuration flags for Secure Memory Region entries.
- AUTH_AAD = (8, 'AUTH_AAD', 'Authentication is computed over [AAD || Plain] image')#
- INSTALL_AUTH = (4, 'INSTALL_AUTH', 'Use installation authentication for verification')#
- MMC_FLASH = (3, 'MMC_FLASH', 'SMR source is in MMC Flash')#
- QSPI_FLASH = (0, 'QSPI_FLASH', 'SMR source is in QSPI Flash')#
- SD_FLASH = (2, 'SD_FLASH', 'SMR source is in SD Flash')#
- class spsdk.image.hse.smr.SmrDecrypt(decrypt_key_handle=<spsdk.image.hse.common.KeyHandle object>, gmac_tag_addr=0, aad_length=0, aad_addr=0)#
Bases:
objectParameters to decrypt an encrypted SMR.
This dataclass encapsulates the parameters needed for SMR (Secure Memory Region) decryption, including key handle, GMAC tag, and AAD (Additional Authenticated Data) information.
The decrypt_key_handle can be initialized as None, but will be automatically set to HSE_SMR_DECRYPT_KEY_HANDLE_NOT_USED in __post_init__ if not provided, ensuring it’s always a valid KeyHandle instance after initialization.
- FORMAT = '<LBBBBL'#
- HSE_SMR_DECRYPT_KEY_HANDLE_NOT_USED = 0#
-
aad_addr:
int= 0# Optional - the address of AAD used for AEAD.
-
aad_length:
int= 0# Optional - the length in bytes of the Authenticated Additional Data (AAD).
-
decrypt_key_handle:
KeyHandle= <spsdk.image.hse.common.KeyHandle object># The key handle referencing the decryption key. If None, SMR is not encrypted.
- export()#
Export SMR decrypt object to binary format.
- Return type:
bytes- Returns:
Binary representation of the SMR decrypt object
- classmethod get_size()#
Get the size of the SMR decrypt structure.
- Return type:
int- Returns:
Size in bytes
-
gmac_tag_addr:
int= 0# Address of the Tag used for GCM. If set to 0, AES-CTR is used for decryption.
- property is_decryption_used: bool#
Check if SMR decryption is used.
- Returns:
True if decryption is used, False otherwise
- classmethod parse(data)#
Parse SMR decrypt parameters from binary data.
- Parameters:
data (
bytes) – Binary data containing SMR decrypt parameters- Return type:
Self- Returns:
SmrDecrypt instance
- Raises:
SPSDKParsingError – If data is invalid
- property size: int#
Get the size of the SMR decrypt structure.
- Returns:
Size in bytes
- class spsdk.image.hse.smr.SmrEntry(family, auth_scheme, smr_src_addr, smr_size, smr_dest, auth_key_handle, config_flags=SmrConfigFlags(tag=0, label='QSPI_FLASH', description='SMR source is in QSPI Flash'), check_period=0, inst_auth_tag=(0, 0), version_offset=0, smr_decrypt=None)#
Bases:
FeatureBaseClassHSE Secure Memory Region Entry.
This class represents a Secure Memory Region (SMR) entry which defines the properties of a memory region that needs to be verified during boot or runtime phase.
Initialize the key information structure.
- Parameters:
family (
FamilyRevision) – Device familyauth_scheme (
AuthScheme) – Key flags defining key propertiessmr_src_addr (
int) – Source address where the SMR needs to be loaded from. This address must be absolute addresssmr_size (
int) – The size in bytes of the SMR to be loaded/verifiedsmr_dest (
int) – Destination address of SMR (where to copy the SMR after authentication)config_flags (
SmrConfigFlags) – Configuration flags of SMR entrycheck_period (
int) – If check_period != 0, HSE verify the SMR entry periodically (in background)auth_key_handle (
KeyHandle) – The key handle used to check the authenticity of the plaintext SMRinst_auth_tag_addrs – The location in external flash of the initial proof of authenticity over SMR
version_offset (
int) – The offset in SMR where the image version can be found.May be used to provide the SMR version which offers anti-rollback protection for the imagesmr_decrypt (
Optional[SmrDecrypt]) – Specifies the parameters for SMR decryption
-
FEATURE:
str= 'hse'#
-
SUB_FEATURE:
Optional[str] = 'smr'#
- export()#
Export the SMR entry to binary format.
- Return type:
bytes- Returns:
Binary representation of the SMR entry
- get_config(data_path='./')#
Get configuration dictionary from SMR entry.
- Return type:
Config- Returns:
Configuration dictionary that can be used to recreate this SMR entry
- classmethod get_validation_schemas(family)#
Create the list of validation schemas.
- Parameters:
family (
FamilyRevision) – The CPU/MPU- Return type:
list[dict[str,Any]]- Returns:
List of validation schemas.
- classmethod load_from_config(config)#
Load SMR entry from configuration.
- Parameters:
config (
Config) – Configuration object containing SMR entry settings- Return type:
Self- Returns:
SmrEntry instance
- Raises:
SPSDKValueError – If configuration is invalid
- classmethod parse(data, family=unknown, Revision: latest)#
Parse SMR entry from binary data.
- Parameters:
data (
bytes) – Binary data containing the SMR entryfamily (
FamilyRevision) – Device family revision
- Return type:
Self- Returns:
SmrEntry instance
- Raises:
SPSDKParsingError – If data is invalid or insufficient
- property size: int#
Get the size of this SMR entry structure.
- Returns:
Size in bytes
- verify()#
Verify SMR entry data and return verification results.
This method performs comprehensive verification of the Secure Memory Region (SMR) entry, including validation of addresses, sizes, alignment, check period, and version offset.
- Return type:
Verifier- Returns:
Verifier object containing detailed verification results and any warnings or errors.
- class spsdk.image.hse.smr.XcbcMacScheme#
Bases:
MacSchemeXCBC-MAC scheme parameters.
-
AUTH_SCH:
AuthSchemeEnum= (19, 'XCBC_MAC', 'XCBC MAC (AES128)')#
-
SCH_FORMAT:
str= '<BBBB'#
- get_config()#
Get configuration dictionary.
- Return type:
dict[str,Any]
- classmethod load_from_config(config)#
Load configuration from config object.
- Return type:
Self
-
AUTH_SCH:
- spsdk.image.hse.smr.prepare_auth_tag_addr_tuple(auth_scheme, auth_tag_addr, auth_tag_length)#
Prepare authentication tag address tuple for SMR entry installation.
For ECDSA and EdDSA schemes, two authentication tag addresses are required. For other schemes (MAC, RSA), only one address is needed, and the second is set to 0.
If only one address is provided for ECDSA/EdDSA, the second address is calculated by adding the first tag length to the first address.
- Parameters:
auth_scheme (
AuthScheme) – Authentication scheme that determines address requirementsauth_tag_addr (
tuple) – Tuple of authentication tag addresses (1 or 2 elements)auth_tag_length (
tuple) – Tuple of authentication tag lengths (used for calculation)
- Return type:
tuple[int,int]- Returns:
Tuple of exactly 2 authentication tag addresses (addr1, addr2)