SBFile Module API

Contents

SBFile Module API#

SPSDK SBFile format implementation.

This module provides functionality for creating, parsing, and manipulating Secure Binary (SB) files used in NXP MCU secure provisioning workflows.

SBFile Version 1#

SPSDK SBFile version 1 implementation.

This module provides complete functionality for creating, parsing, and manipulating Secure Binary (SB) files version 1, including headers, sections, images, and related utilities for NXP MCU secure boot process.

class spsdk.sbfile.sb1.BcdVersion3(major=1, minor=0, service=0)#

Bases: object

BCD version representation for three-component version numbers.

This class handles version numbers in the format major.minor.service where each component is a BCD (Binary Coded Decimal) number with 1-4 digits. It provides validation, parsing, and conversion functionality for version strings used in SPSDK operations.

Variables:

DEFAULT – Default version string template.

Initialize BcdVersion3.

Parameters:
  • major (int) – Major version number in BCD format, 1-4 decimal digits.

  • minor (int) – Minor version number in BCD format, 1-4 decimal digits.

  • service (int) – Service version number in BCD format, 1-4 decimal digits.

Raises:

SPSDKError – Invalid version number provided.

DEFAULT = '999.999.999'#
static from_str(text)#

Convert string to BcdVersion3 instance.

Parses a version string in the format major.minor.service where each component is a 1-4 decimal digit number and creates a corresponding BcdVersion3 object.

Parameters:

text (str) – Version string in format #.#.#, where # is 1-4 decimal digits.

Return type:

BcdVersion3

Returns:

BcdVersion3 instance created from the parsed version string.

Raises:

SPSDKError – If the format is not valid or contains invalid components.

property nums: Sequence[int]#

Get version numbers as a sequence.

Returns:

Array of version numbers in format [major, minor, service].

static to_version(input_version)#

Convert different input formats into BcdVersion3 instance.

The method accepts either a BcdVersion3 object directly or a string representation and converts it to a BcdVersion3 instance.

Parameters:

input_version (Union[BcdVersion3, str]) – Either a BcdVersion3 object or string representation of version

Raises:

SPSDKError – When the input format is unsupported

Return type:

BcdVersion3

Returns:

BcdVersion3 instance

class spsdk.sbfile.sb1.BootSectionV1(section_id, flags=SecureBootFlagsV1(tag=0, label='NONE', description='No flags'))#

Bases: BaseClass

Boot Section for SB file version 1.x.

This class represents a boot section within a Secure Binary (SB) file format version 1.x, managing section metadata through its header and containing a collection of boot commands. The section can be configured as bootable and includes flags for ROM processing control.

Initialize BootSectionV1.

Parameters:
  • section_id (int) – Unique section ID, 32-bit integer value.

  • flags (SecureBootFlagsV1) – Boot section flags, see SecureBootFlagsV1 enumeration.

append(cmd)#

Append command to the section.

Adds a new command to the internal commands list. The command must be one of the supported SB1 command types.

Parameters:

cmd (CmdBaseClass) – Command instance to be added to the section

Raises:

AssertionError – If the command type is not supported

Return type:

None

property bootable: bool#

Return whether section is bootable.

Returns:

True if section is bootable, False otherwise.

property cmd_size: int#

Calculate the total size of all commands in binary representation.

Returns:

Total size in bytes of all commands when serialized to binary format.

property commands: Sequence[CmdBaseClass]#

Return sequence of all commands in the section.

Returns:

Sequence of all commands contained in this section.

export()#

Export section to binary representation.

The method updates the section header and serializes all commands into a binary format suitable for storage or transmission.

Return type:

bytes

Returns:

Binary data representing the complete section including header and commands.

property flags: SecureBootFlagsV1#

Get section flags.

Returns:

Section flags containing security and operational settings.

classmethod parse(data)#

Parse boot section from binary data format.

Deserializes binary data into a boot section instance by parsing the header and extracting all commands within the section blocks.

Parameters:

data (bytes) – Binary data to be parsed into boot section.

Return type:

Self

Returns:

Parsed boot section instance with header and commands.

property rom_last_tag: bool#

Get ROM_LAST_TAG flag.

The last section header in an image always has its ROM_LAST_TAG flag set to help the ROM know at what point to stop searching.

Returns:

True if this is the last section, False otherwise.

property section_id: int#

Get unique ID of the section.

Returns the 32-bit unique identifier of the section from the header.

Returns:

Section unique identifier as 32-bit integer.

property size: int#

Return size of the binary representation of the section in bytes.

Returns:

Size in bytes including header and command data.

update()#

Update the internal settings of the section.

This method recalculates and updates the number of blocks in the header based on the current command size.

Raises:

SPSDKError – If block size calculation fails.

Return type:

None

class spsdk.sbfile.sb1.CmdCall(address=0, argument=0)#

Bases: CmdBaseClass

SB2 Call command for bootloader function execution.

This command represents a bootloader call instruction that executes a function from files previously loaded into memory. It encapsulates the target address and optional argument for the function call operation.

Initialize Command Call.

Parameters:
  • address (int) – Memory address for the call command, defaults to 0.

  • argument (int) – Additional argument for the call command, defaults to 0.

property address: int#

Return command’s address.

Returns:

The address value stored in the command header.

property argument: int#

Get command’s argument value.

Returns:

The argument value stored in the command header.

classmethod parse(data)#

Parse command from bytes array into Command Call object.

This method validates the command header tag and creates a new Command Call instance with the parsed address and data from the input bytes.

Parameters:

data (bytes) – Input data as bytes array containing command information

Return type:

Self

Returns:

Command Call object with parsed address and data

Raises:

SPSDKError – If incorrect header tag is found in the data

class spsdk.sbfile.sb1.CmdErase(address=0, length=0, flags=0, mem_id=0)#

Bases: CmdBaseClass

SB2 erase command for memory operations.

This command handles erasing operations on target memory devices, allowing specification of memory address, length, and device-specific flags. The command automatically manages device and group ID encoding within the flags field.

Initialize Command Erase.

Creates an erase command with specified memory address, length, and flags. The constructor automatically sets device ID and group ID in the flags based on mem_id.

Parameters:
  • address (int) – Memory address to start erasing from.

  • length (int) – Number of bytes to erase.

  • flags (int) – Command flags for erase operation.

  • mem_id (int) – Memory identifier used to extract device and group IDs.

property address: int#

Get command’s address.

Returns:

The address value stored in the command header.

property flags: int#

Return command’s flags value.

Returns:

The flags value from the command header.

property length: int#

Return command’s count.

Returns:

Number of commands in the command block.

classmethod parse(data)#

Parse command from bytes array into CmdErase object.

Extracts header information and validates the command tag. Decodes device ID and group ID from header flags to determine memory ID for the erase operation.

Parameters:

data (bytes) – Input data as bytes containing the command structure

Raises:

SPSDKError – If incorrect header tag for erase command

Return type:

Self

Returns:

CmdErase object with parsed address, count, flags and memory ID

class spsdk.sbfile.sb1.CmdFill(address, pattern, length=None, zero_filling=False)#

Bases: CmdBaseClass

SB2 Fill command for memory initialization operations.

This command fills a specified memory range with a given pattern, supporting various data patterns and lengths. The fill operation ensures proper alignment and handles pattern conversion for secure boot file generation.

Variables:

PADDING_VALUE – Default padding value used for alignment operations.

Initialize Command Fill.

Creates a fill command that writes a pattern to a specified memory address. The pattern is replicated to fill the specified length of memory. The pattern must be 1, 2, or 4 bytes long and will be automatically replicated to create a 4-byte pattern for efficient memory filling.

Parameters:
  • address (int) – Memory address where data should be written.

  • pattern (int) – Data pattern to be written (integer value).

  • length (Optional[int]) – Length of memory range to fill in bytes, defaults to 4.

  • zero_filling (bool) – Flag indicating if this is zero filling operation.

Raises:

SPSDKError – Length is not aligned to 4 bytes or pattern size invalid.

PADDING_VALUE = 0#
property address: int#

Get address of the command Fill.

Returns:

Address value of the Fill command.

export()#

Export command in binary form with proper alignment.

The method serializes the command to binary format and applies block alignment using either zero filling or random filling based on the zero_filling flag.

Return type:

bytes

Returns:

Serialized command data with proper block alignment.

classmethod parse(data)#

Parse command from bytes.

Parses the binary data to create a Fill command object by extracting and validating the command header information.

Parameters:

data (bytes) – Input data as bytes containing the command structure

Return type:

Self

Returns:

Command Fill object

Raises:

SPSDKError – If incorrect header tag

property pattern: bytes#

Return binary data pattern used for filling.

Returns:

Binary data pattern as bytes.

property raw_size: int#

Calculate raw size of the command header.

The method calculates the total size including the pattern length minus 4 bytes, with padding to align to CmdHeader.SIZE boundary.

Returns:

Raw size of the header in bytes.

class spsdk.sbfile.sb1.CmdJump(address=0, argument=0, spreg=None)#

Bases: CmdBaseClass

SB2 Jump command for transferring execution control.

This command represents a jump instruction in SB2 (Secure Binary) files that transfers program execution to a specified memory address. It supports optional stack pointer configuration and can carry additional arguments for the target execution context.

Initialize Command Jump.

Parameters:
  • address (int) – Jump target address, defaults to 0.

  • argument (int) – Additional argument for jump command, defaults to 0.

  • spreg (Optional[int]) – Optional stack pointer register value.

property address: int#

Get the address of the Jump command.

Returns:

Address value of the Jump command.

property argument: int#

Get command’s argument value.

Returns:

The argument value stored in the command header.

classmethod parse(data)#

Parse command from bytes.

Parses the input byte data to create a Jump command object by extracting and validating the command header information.

Parameters:

data (bytes) – Input data as bytes containing the command structure.

Return type:

Self

Returns:

Command Jump object created from parsed data.

Raises:

SPSDKError – If incorrect header tag is found in the data.

property spreg: int | None#

Return command’s Stack Pointer.

The Stack Pointer value is only available when the command header flags field is set to 2, indicating that the count field contains the stack pointer value.

Returns:

Stack pointer value if flags equals 2, None otherwise.

class spsdk.sbfile.sb1.CmdLoad(address, data, mem_id=0, zero_filling=False)#

Bases: CmdBaseClass

SB2 Load Command for memory data operations.

This command class represents a load operation that stores data into target processor memory at a specified address. It handles memory addressing, data alignment, and provides functionality for exporting and parsing load commands in SB2 format.

Initialize CMD Load command.

Creates a new Load command that writes data to a specified memory address. The command supports different memory interfaces through mem_id parameter and can be configured for zero filling behavior.

Parameters:
  • address (int) – Target memory address where data will be written.

  • data (bytes) – Binary data to be loaded into memory.

  • mem_id (int) – Memory interface identifier, defaults to 0.

  • zero_filling (bool) – Enable zero filling for unaligned data, defaults to False.

property address: int#

Return address in target processor to load data.

Returns:

Address value where data should be loaded in target processor memory.

export()#

Export command as binary data.

Updates internal data before exporting the command and appends the command’s data to the base export result.

Return type:

bytes

Returns:

Binary representation of the command including its data.

property flags: int#

Return command’s flag.

Returns:

Command flags as integer value.

classmethod parse(data)#

Parse command from bytes.

This method parses a LOAD command from binary data by extracting and validating the command header, verifying CRC integrity, and reconstructing the command object with proper memory identification.

Parameters:

data (bytes) – Input data as bytes containing the command structure.

Return type:

Self

Returns:

CMD Load object parsed from the input data.

Raises:
  • SPSDKError – Raised when there is invalid CRC in the command header.

  • SPSDKError – When there is incorrect header tag (not LOAD command).

property raw_size: int#

Calculate aligned size of the command including header and data.

The method calculates the total size by adding the header size and data length, then aligns the result to the nearest multiple of header size for proper memory alignment.

Returns:

Aligned size in bytes including command header and data payload.

class spsdk.sbfile.sb1.CmdMemEnable(address, size, mem_id)#

Bases: CmdBaseClass

SB2 command to enable and configure memory initialization.

This command configures memory devices by specifying the source address of configuration data, the size of that data, and the target memory identifier. It manages memory device and group identification through flag manipulation.

Initialize CmdMemEnable command.

This command enables and configures memory using the provided configuration data. The method extracts device and group IDs from the memory ID and sets appropriate flags for memory initialization.

Parameters:
  • address (int) – Source address with configuration data for memory initialization.

  • size (int) – Size of configuration data used for memory initialization.

  • mem_id (int) – Identification of memory containing device and group information.

property address: int#

Return command’s address.

Returns:

The address value stored in the command header.

property flags: int#

Return command’s flag.

Returns:

Command flags as integer value.

classmethod parse(data)#

Parse Memory Enable command from binary data.

This method extracts device ID and group ID from the command header flags and constructs a Memory Enable command object with the parsed parameters.

Parameters:

data (bytes) – Binary data containing the Memory Enable command structure.

Raises:

SPSDKError – If the header tag is not MEM_ENABLE.

Return type:

Self

Returns:

Parsed Memory Enable command object.

property size: int#

Return command’s size in bytes.

Returns:

Size of the command including header.

class spsdk.sbfile.sb1.CmdNop#

Bases: CmdBaseClass

SB2 No Operation command implementation.

This class represents a NOP (No Operation) command in the SB2 file format, which serves as a placeholder or padding command that performs no actual operation when executed by the target device.

Initialize Command Nop.

Creates a new NOP (No Operation) command instance that performs no action when executed. This command is typically used as a placeholder or for timing purposes in command sequences.

classmethod parse(data)#

Parse command from bytes array into CMD Nop object.

This method validates the command header tag and creates a new CMD Nop instance if the header contains the correct NOP tag.

Parameters:

data (bytes) – Input data as bytes array containing the command structure

Return type:

Self

Returns:

CMD Nop object instance

Raises:

SPSDKError – When there is incorrect header tag

class spsdk.sbfile.sb1.CmdProg(address, mem_id, data_word1, data_word2=0, flags=0)#

Bases: CmdBaseClass

SB2.1 Program command for writing data to target memory.

This command handles programming operations in SB2.1 secure boot files, allowing data to be written to specific memory addresses on the target processor. It manages the target address, command flags, and associated data words for the programming operation.

Initialize CMD Prog command.

Creates a new program command for writing data to memory with specified address, memory ID, and data words. Supports both 4-byte and 8-byte data operations.

Parameters:
  • address (int) – Target memory address for programming operation.

  • mem_id (int) – Memory device identifier (0-255).

  • data_word1 (int) – First 32-bit data word to program.

  • data_word2 (int) – Second 32-bit data word for 8-byte operations, defaults to 0.

  • flags (int) – Additional command flags, defaults to 0.

Raises:

SPSDKError – Invalid memory ID (must be 0-255).

property address: int#

Return address in target processor to program data.

Returns:

Address value for programming data in target processor.

property data_word1: int#

Return data word 1.

Get the count value from the header which represents the first data word in the command structure.

Returns:

The count value from the header as data word 1.

property data_word2: int#

Return data word 2.

Returns:

The value of data word 2 from the header.

property flags: int#

Return command’s flags value.

Returns:

The flags value from the command header.

classmethod parse(data)#

Parse command from bytes.

The method parses the input byte data to create a command object by extracting header information and validating the command tag.

Parameters:

data (bytes) – Input data as bytes to be parsed into command object.

Raises:

SPSDKError – If incorrect header tag is found in the data.

Return type:

Self

Returns:

Parsed command object instance.

class spsdk.sbfile.sb1.CmdReset#

Bases: CmdBaseClass

SB2 Reset command implementation.

This class represents a reset command in the SB2 (Secure Binary 2) file format, which instructs the target device to perform a system reset operation.

Initialize Command Reset.

Initializes a new Reset command instance by calling the parent constructor with the RESET command tag.

classmethod parse(data)#

Parse command from bytes array.

Parses the binary data to create a Reset command object by first validating the command header tag matches the expected RESET tag.

Parameters:

data (bytes) – Input data as bytes array containing the command structure.

Raises:

SPSDKError – If incorrect header tag found in the data.

Return type:

Self

Returns:

Cmd Reset object instance.

class spsdk.sbfile.sb1.CmdTag#

Bases: CmdBaseClass

Command TAG class for SB file operations.

This class represents a TAG command used in Secure Binary (SB) files and serves as a header for boot sections in SB file version 1.x. It provides functionality for creating and parsing TAG commands within the SB file structure.

Initialize Command Tag.

Initialize a new Command Tag instance by calling the parent constructor with the TAG enumeration value.

classmethod parse(data)#

Parse command from bytes array.

Parses the binary data to create a command instance by extracting and validating the command header information.

Parameters:

data (bytes) – Input data as bytes array containing command information.

Raises:

SPSDKError – When there is incorrect header tag.

Return type:

Self

Returns:

Parsed command instance.

class spsdk.sbfile.sb1.SecureBootFlagsV1(tag, label, description=None)#

Bases: SpsdkEnum

Secure Binary flags enumeration for SB1 format section headers.

This enumeration defines the available flags that can be applied to sections in Secure Binary version 1 format, controlling section behavior such as bootability and encryption settings.

NONE = (0, 'NONE', 'No flags')#
ROM_SECTION_BOOTABLE = (1, 'ROM_SECTION_BOOTABLE', 'The section is bootable and contains a sequence of bootloader commands.')#
ROM_SECTION_CLEARTEXT = (2, 'ROM_SECTION_CLEARTEXT', 'The section is unencrypted. Applies only if the rest of the boot image is encrypted.')#
class spsdk.sbfile.sb1.SecureBootV1(version='1.0', flags=0, drive_tag=0, product_version='999.999.999', component_version='999.999.999', dek=None, mac=None, digest=b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', timestamp=None)#

Bases: BaseClass

Secure Binary file format version 1.x container.

This class represents and manages SB (Secure Binary) file format version 1.x, providing functionality to create, validate, and export secure boot images for NXP MCUs. It handles the complete structure including headers, sections, and cryptographic elements required for secure boot operations.

Initialize Secure Binary Image V1.x.

Creates a new instance of SecureBootImageV1 with specified parameters for boot image generation. The image supports both version 1.1 and 1.2 formats with optional encryption capabilities.

Parameters:
  • version (str) – Version string in format #.# (major.minor), currently supports 1.1 or 1.2.

  • flags (int) – Header flags associated with the entire image, defaults to 0.

  • drive_tag (int) – Identifier for the disk drive or partition containing this image.

  • product_version (Union[BcdVersion3, str]) – Product version in BCD format.

  • component_version (Union[BcdVersion3, str]) – Component version in BCD format.

  • dek (Optional[bytes]) – DEK key for encrypted SB file (encryption not yet supported), generates random if None.

  • mac (Optional[bytes]) – MAC for encrypted SB file (encryption not yet supported), generates random if None.

  • digest (bytes) – SHA-1 digest of header fields, updated before export. First 16 bytes serve as IV for CBC-encrypted regions.

  • timestamp (Optional[datetime]) – File creation timestamp, uses current time if None. Fixed values should only be used for regression testing.

append(section)#

Add section into the SB file.

Parameters:

section (BootSectionV1) – Boot section to be added to the file

Raises:

AssertionError – If section is not an instance of BootSectionV1

Return type:

None

export(header_padding8=None, auth_padding=None)#

Export the SB1 image to binary format.

The method serializes the complete SB1 image including header, section table, sections data, authentication hash, and padding to create the final binary output.

Parameters:
  • header_padding8 (Optional[bytes]) – Optional header padding, 8-bytes; recommended to use None to apply random value

  • auth_padding (Optional[bytes]) – Optional padding used after authentication; recommended to use None to apply random value

Return type:

bytes

Returns:

Binary representation of the SB1 image

Raises:

SPSDKError – Invalid section data or invalid padding length

property first_boot_section_id: int#

Get the ID of the first boot section.

Returns:

ID of the first boot section.

classmethod parse(data)#

Parse binary data into SecureBoot image instance.

Deserializes binary data by parsing the secure boot header, section header table, boot sections, and validates the authentication digest.

Parameters:

data (bytes) – Binary data to be deserialized into SecureBoot image instance.

Return type:

Self

Returns:

Parsed SecureBoot image instance.

Raises:
  • SPSDKError – Invalid section positioning detected.

  • SPSDKError – Authentication failure when digest does not match.

property sections: Sequence[BootSectionV1]#

Return sequence of all sections in the SB file.

Returns:

Sequence containing all boot sections present in the SB file.

property size: int#

Return size of the binary representation in bytes.

Calculates the total size by summing the header size, all section header sizes, all section sizes, and the authentication data size (32 bytes).

Returns:

Total size in bytes of the binary representation.

update()#

Update the secure boot file content.

This method synchronizes all internal structures including header section count, ROM_LAST_TAG flags for bootable sections, section header table with proper offsets and block counts, and overall image size in blocks.

Return type:

None

validate()#

Validate the image settings for consistency.

Ensures that the image configuration is valid and contains all required sections before processing.

Raises:

SPSDKError – If no sections are defined or settings are inconsistent.

Return type:

None

SBFile Version 1 commands#

SPSDK SB1 command parsing and management utilities.

This module provides functionality for parsing and handling SB1 (Secure Binary version 1) commands within the SPSDK framework. It includes command parsing capabilities and integrates with the SB2 command infrastructure for unified command processing.

spsdk.sbfile.sb1.commands.parse_v1_command(data)#

Parse SB V1.x command from binary format.

This method extracts the command tag from the binary data and creates the appropriate command object based on the tag type.

Parameters:

data (bytes) – Input binary data containing the SB V1.x command

Raises:

SPSDKError – Raised when there is unsupported command tag

Return type:

CmdBaseClass

Returns:

Parsed command object instance

SBFile Version 1 headers#

SPSDK Secure Binary v1 header structures and utilities.

This module provides classes for handling Secure Binary version 1 headers, including boot flags, main boot headers, section headers, and boot section headers used in SB1 file format processing.

class spsdk.sbfile.sb1.headers.BootSectionHeaderV1(section_id=0, flags=SecureBootFlagsV1(tag=0, label='NONE', description='No flags'))#

Bases: CmdTag

Boot section header for Secure Binary version 1.

This class represents a header for boot sections in SB1 files, derived from command TAG structure. The command TAG was reused to save code in Boot ROM. It manages section identification, block counting, and ROM flags for proper boot sequence handling.

Variables:

SIZE – Size of the binary representation of the header in bytes.

Initialize BootSectionHeaderV1.

Parameters:
  • section_id (int) – Unique section ID as 32-bit integer.

  • flags (SecureBootFlagsV1) – Secure boot flags, see SecureBootFlagsV1 enumeration.

SIZE = 16#
property bootable: bool#

Return whether section is bootable.

Returns:

True if the section has the bootable flag set, False otherwise.

property flags: SecureBootFlagsV1#

Get section flags from header data.

Returns:

Section flags parsed from the header data.

property num_blocks: int#

Return size of the section in number of cipher blocks.

Returns:

Number of cipher blocks in the section.

classmethod parse(data)#

Parse bytes data into BootSectionHeaderV1 object.

Parameters:

data (bytes) – Raw bytes data to be parsed into header object.

Return type:

Self

Returns:

Parsed BootSectionHeaderV1 instance.

property rom_last_tag: bool#

Get ROM_LAST_TAG flag status.

The last section header in an image always has its ROM_LAST_TAG flag set to help the ROM know at what point to stop searching.

Returns:

True if ROM_LAST_TAG flag is set, False otherwise.

property section_id: int#

Return unique ID of the section.

The section ID is a 32-bit number derived from the header address that uniquely identifies this section within the SB file structure.

Returns:

Section unique identifier as 32-bit integer.

class spsdk.sbfile.sb1.headers.SectionHeaderItemV1(identifier=0, offset=0, num_blocks=0, flags=SecureBootFlagsV1(tag=0, label='NONE', description='No flags'))#

Bases: BaseClass

Section header item representing a single entry in the section header table of SB file V1.x.

This class encapsulates the metadata for individual sections within Secure Binary V1.x files, including section identification, data location, size information, and behavioral flags.

Variables:
  • FORMAT – Binary format string for section header serialization.

  • SIZE – Size of the section header item in bytes.

Initialize SectionHeaderItemV1.

Creates a new section header item for SB1 file format with specified parameters.

Parameters:
  • identifier (int) – Unique 32-bit identifier for this section.

  • offset (int) – The starting cipher block for this section’s data from the beginning of the image.

  • num_blocks (int) – The length of the section data in cipher blocks.

  • flags (SecureBootFlagsV1) – Flags that apply to the entire section, see SecureBootFlagsV1.

FORMAT = '<4I'#
SIZE = 16#
property bootable: bool#

Return whether section is bootable.

Returns:

True if section has bootable flag set, False otherwise.

export()#

Export header data to binary format.

Serializes the header structure into binary representation using the defined FORMAT.

Return type:

bytes

Returns:

Binary representation of the header data.

property flags: int#

Return flags value from the section header.

The flags indicate various properties and settings for the section, as defined in SectionHeaderV1Flags enumeration.

Returns:

Integer value representing the section flags.

classmethod parse(data)#

Parse binary data into SB1 header instance.

Deserializes the provided binary data into a new header instance by unpacking the structured data according to the class format specification.

Parameters:

data (bytes) – Binary data to be parsed into header instance.

Raises:

SPSDKError – If data size is insufficient for parsing.

Return type:

Self

Returns:

New header instance created from the parsed data.

property size: int#

Return size of exported data in bytes.

Returns:

Size of the exported data in bytes.

class spsdk.sbfile.sb1.headers.SecureBootFlagsV1(tag, label, description=None)#

Bases: SpsdkEnum

Secure Binary flags enumeration for SB1 format section headers.

This enumeration defines the available flags that can be applied to sections in Secure Binary version 1 format, controlling section behavior such as bootability and encryption settings.

NONE = (0, 'NONE', 'No flags')#
ROM_SECTION_BOOTABLE = (1, 'ROM_SECTION_BOOTABLE', 'The section is bootable and contains a sequence of bootloader commands.')#
ROM_SECTION_CLEARTEXT = (2, 'ROM_SECTION_CLEARTEXT', 'The section is unencrypted. Applies only if the rest of the boot image is encrypted.')#
label: str#
tag: int#
class spsdk.sbfile.sb1.headers.SecureBootHeaderV1(version='1.0', product_version='999.999.999', component_version='999.999.999', flags=0, drive_tag=0, digest=b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', timestamp=None)#

Bases: BaseClass

Secure Binary Header V1.

This class represents and manages the header structure for Secure Binary version 1 format used in NXP MCU boot images. It handles the binary format, validation, and serialization of boot image headers including version information, security flags, and cryptographic digests.

Variables:
  • _SIGNATURE1 – Binary signature ‘STMP’ for header identification.

  • _SIGNATURE2 – Binary signature ‘sgtl’ for header identification.

Initialize SecureBootHeaderV1.

Creates a new instance of SecureBootHeaderV1 with the specified parameters for secure boot image generation.

Parameters:
  • version (str) – Boot image format version, must be “1.0”, “1.1”, or “1.2”.

  • product_version (Union[BcdVersion3, str]) – Product version in BCD format.

  • component_version (Union[BcdVersion3, str]) – Component version in BCD format.

  • flags (int) – Flags associated with the entire image.

  • drive_tag (int) – Identifier for the disk drive or partition containing this image.

  • digest (bytes) – SHA-1 digest of header fields (20 bytes). First 16 bytes serve as CBC initialization vector.

  • timestamp (Optional[datetime]) – Creation timestamp. Use None for current time. Fixed values should only be used for regression testing.

Raises:

SPSDKError – Invalid header version provided.

export(padding8=None)#

Export header to binary format.

Serializes the header object into its binary representation with proper formatting and padding. The digest is calculated and prepended to the final result.

Parameters:

padding8 (Optional[bytes]) – Optional 8-byte padding for header, uses random bytes if None. Should only be specified for regression testing to ensure reproducible results.

Return type:

bytes

Returns:

Binary representation of the header with digest prepended.

property first_boot_tag_block: int#

Get the first boot tag block index.

Calculates the position of the first boot tag block based on the key dictionary block position and the number of keys present.

Returns:

Index of the first boot tag block.

property key_dictionary_block: int#

Get the key dictionary block offset.

Calculates the offset to the key dictionary block by adding the header blocks and the total size of all section headers.

Returns:

Offset to the key dictionary block in bytes.

classmethod parse(data)#

Parse binary data into SecureBootHeaderV1 instance.

Deserializes binary data containing a secure boot header version 1 into a structured object. The method validates header signatures and version compatibility during parsing.

Parameters:

data (bytes) – Binary data to be decoded into header instance.

Return type:

Self

Returns:

Parsed secure boot header v1 instance.

Raises:
  • SPSDKError – Insufficient data size for header parsing.

  • SPSDKError – Invalid or unexpected header signature found.

property size: int#

Return size of the header in bytes.

Returns:

Size of the header in bytes.

SBFile Version 1 images#

SPSDK Secure Binary version 1 image handling.

This module provides functionality for creating and managing Secure Binary v1 images in SPSDK context, including image generation, validation, and manipulation.

class spsdk.sbfile.sb1.images.SecureBootV1(version='1.0', flags=0, drive_tag=0, product_version='999.999.999', component_version='999.999.999', dek=None, mac=None, digest=b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00', timestamp=None)#

Bases: BaseClass

Secure Binary file format version 1.x container.

This class represents and manages SB (Secure Binary) file format version 1.x, providing functionality to create, validate, and export secure boot images for NXP MCUs. It handles the complete structure including headers, sections, and cryptographic elements required for secure boot operations.

Initialize Secure Binary Image V1.x.

Creates a new instance of SecureBootImageV1 with specified parameters for boot image generation. The image supports both version 1.1 and 1.2 formats with optional encryption capabilities.

Parameters:
  • version (str) – Version string in format #.# (major.minor), currently supports 1.1 or 1.2.

  • flags (int) – Header flags associated with the entire image, defaults to 0.

  • drive_tag (int) – Identifier for the disk drive or partition containing this image.

  • product_version (Union[BcdVersion3, str]) – Product version in BCD format.

  • component_version (Union[BcdVersion3, str]) – Component version in BCD format.

  • dek (Optional[bytes]) – DEK key for encrypted SB file (encryption not yet supported), generates random if None.

  • mac (Optional[bytes]) – MAC for encrypted SB file (encryption not yet supported), generates random if None.

  • digest (bytes) – SHA-1 digest of header fields, updated before export. First 16 bytes serve as IV for CBC-encrypted regions.

  • timestamp (Optional[datetime]) – File creation timestamp, uses current time if None. Fixed values should only be used for regression testing.

append(section)#

Add section into the SB file.

Parameters:

section (BootSectionV1) – Boot section to be added to the file

Raises:

AssertionError – If section is not an instance of BootSectionV1

Return type:

None

export(header_padding8=None, auth_padding=None)#

Export the SB1 image to binary format.

The method serializes the complete SB1 image including header, section table, sections data, authentication hash, and padding to create the final binary output.

Parameters:
  • header_padding8 (Optional[bytes]) – Optional header padding, 8-bytes; recommended to use None to apply random value

  • auth_padding (Optional[bytes]) – Optional padding used after authentication; recommended to use None to apply random value

Return type:

bytes

Returns:

Binary representation of the SB1 image

Raises:

SPSDKError – Invalid section data or invalid padding length

property first_boot_section_id: int#

Get the ID of the first boot section.

Returns:

ID of the first boot section.

classmethod parse(data)#

Parse binary data into SecureBoot image instance.

Deserializes binary data by parsing the secure boot header, section header table, boot sections, and validates the authentication digest.

Parameters:

data (bytes) – Binary data to be deserialized into SecureBoot image instance.

Return type:

Self

Returns:

Parsed SecureBoot image instance.

Raises:
  • SPSDKError – Invalid section positioning detected.

  • SPSDKError – Authentication failure when digest does not match.

property sections: Sequence[BootSectionV1]#

Return sequence of all sections in the SB file.

Returns:

Sequence containing all boot sections present in the SB file.

property size: int#

Return size of the binary representation in bytes.

Calculates the total size by summing the header size, all section header sizes, all section sizes, and the authentication data size (32 bytes).

Returns:

Total size in bytes of the binary representation.

update()#

Update the secure boot file content.

This method synchronizes all internal structures including header section count, ROM_LAST_TAG flags for bootable sections, section header table with proper offsets and block counts, and overall image size in blocks.

Return type:

None

validate()#

Validate the image settings for consistency.

Ensures that the image configuration is valid and contains all required sections before processing.

Raises:

SPSDKError – If no sections are defined or settings are inconsistent.

Return type:

None

SBFile Version 1 sections#

SPSDK SB1 boot sections implementation.

This module provides functionality for handling boot sections in SB1 (Secure Binary version 1) files, including section parsing, validation, and management within the SPSDK framework.

class spsdk.sbfile.sb1.sections.BootSectionV1(section_id, flags=SecureBootFlagsV1(tag=0, label='NONE', description='No flags'))#

Bases: BaseClass

Boot Section for SB file version 1.x.

This class represents a boot section within a Secure Binary (SB) file format version 1.x, managing section metadata through its header and containing a collection of boot commands. The section can be configured as bootable and includes flags for ROM processing control.

Initialize BootSectionV1.

Parameters:
  • section_id (int) – Unique section ID, 32-bit integer value.

  • flags (SecureBootFlagsV1) – Boot section flags, see SecureBootFlagsV1 enumeration.

append(cmd)#

Append command to the section.

Adds a new command to the internal commands list. The command must be one of the supported SB1 command types.

Parameters:

cmd (CmdBaseClass) – Command instance to be added to the section

Raises:

AssertionError – If the command type is not supported

Return type:

None

property bootable: bool#

Return whether section is bootable.

Returns:

True if section is bootable, False otherwise.

property cmd_size: int#

Calculate the total size of all commands in binary representation.

Returns:

Total size in bytes of all commands when serialized to binary format.

property commands: Sequence[CmdBaseClass]#

Return sequence of all commands in the section.

Returns:

Sequence of all commands contained in this section.

export()#

Export section to binary representation.

The method updates the section header and serializes all commands into a binary format suitable for storage or transmission.

Return type:

bytes

Returns:

Binary data representing the complete section including header and commands.

property flags: SecureBootFlagsV1#

Get section flags.

Returns:

Section flags containing security and operational settings.

classmethod parse(data)#

Parse boot section from binary data format.

Deserializes binary data into a boot section instance by parsing the header and extracting all commands within the section blocks.

Parameters:

data (bytes) – Binary data to be parsed into boot section.

Return type:

Self

Returns:

Parsed boot section instance with header and commands.

property rom_last_tag: bool#

Get ROM_LAST_TAG flag.

The last section header in an image always has its ROM_LAST_TAG flag set to help the ROM know at what point to stop searching.

Returns:

True if this is the last section, False otherwise.

property section_id: int#

Get unique ID of the section.

Returns the 32-bit unique identifier of the section from the header.

Returns:

Section unique identifier as 32-bit integer.

property size: int#

Return size of the binary representation of the section in bytes.

Returns:

Size in bytes including header and command data.

update()#

Update the internal settings of the section.

This method recalculates and updates the number of blocks in the header based on the current command size.

Raises:

SPSDKError – If block size calculation fails.

Return type:

None

SBFile Version 2#

SPSDK SB2 and SB2.1 secure boot file format implementation.

This module provides functionality for creating, parsing, and manipulating SB2 and SB2.1 secure boot files used in NXP MCU secure boot process.

SBFile Version 2 commands#

SPSDK SB2.1 file format command definitions and implementations.

This module provides command classes and utilities for creating and parsing SB2.1 (Secure Binary) file format commands. It includes base command functionality, specific command implementations for operations like load, fill, jump, erase, and utilities for device and memory identification.

class spsdk.sbfile.sb2.commands.CmdBaseClass(tag)#

Bases: BaseClass

Base class for all SB2 commands.

This class provides the foundation for all Secure Binary 2.0 command implementations, managing common command structure including headers and basic serialization functionality.

Variables:
  • ROM_MEM_DEVICE_ID_MASK – Bit mask for extracting device ID from flags.

  • ROM_MEM_DEVICE_ID_SHIFT – Bit shift value for device ID within flags.

  • ROM_MEM_GROUP_ID_MASK – Bit mask for extracting group ID from flags.

  • ROM_MEM_GROUP_ID_SHIFT – Bit shift value for group ID within flags.

Initialize CmdBase.

Parameters:

tag (EnumCmdTag) – Command tag enumeration value used to set the header tag.

ROM_MEM_DEVICE_ID_MASK = 65280#
ROM_MEM_DEVICE_ID_SHIFT = 8#
ROM_MEM_GROUP_ID_MASK = 240#
ROM_MEM_GROUP_ID_SHIFT = 4#
export()#

Export object as serialized byte representation.

This method provides the default implementation for object serialization by delegating to the header’s export functionality.

Return type:

bytes

Returns:

Serialized object data as bytes.

property header: CmdHeader#

Return command header.

Returns:

Command header object containing header information.

property raw_size: int#

Return size of the command in binary format (including header).

Returns:

Size of the command in bytes, defaults to header size only.

class spsdk.sbfile.sb2.commands.CmdCall(address=0, argument=0)#

Bases: CmdBaseClass

SB2 Call command for bootloader function execution.

This command represents a bootloader call instruction that executes a function from files previously loaded into memory. It encapsulates the target address and optional argument for the function call operation.

Initialize Command Call.

Parameters:
  • address (int) – Memory address for the call command, defaults to 0.

  • argument (int) – Additional argument for the call command, defaults to 0.

property address: int#

Return command’s address.

Returns:

The address value stored in the command header.

property argument: int#

Get command’s argument value.

Returns:

The argument value stored in the command header.

classmethod parse(data)#

Parse command from bytes array into Command Call object.

This method validates the command header tag and creates a new Command Call instance with the parsed address and data from the input bytes.

Parameters:

data (bytes) – Input data as bytes array containing command information

Return type:

Self

Returns:

Command Call object with parsed address and data

Raises:

SPSDKError – If incorrect header tag is found in the data

class spsdk.sbfile.sb2.commands.CmdErase(address=0, length=0, flags=0, mem_id=0)#

Bases: CmdBaseClass

SB2 erase command for memory operations.

This command handles erasing operations on target memory devices, allowing specification of memory address, length, and device-specific flags. The command automatically manages device and group ID encoding within the flags field.

Initialize Command Erase.

Creates an erase command with specified memory address, length, and flags. The constructor automatically sets device ID and group ID in the flags based on mem_id.

Parameters:
  • address (int) – Memory address to start erasing from.

  • length (int) – Number of bytes to erase.

  • flags (int) – Command flags for erase operation.

  • mem_id (int) – Memory identifier used to extract device and group IDs.

property address: int#

Get command’s address.

Returns:

The address value stored in the command header.

property flags: int#

Return command’s flags value.

Returns:

The flags value from the command header.

property length: int#

Return command’s count.

Returns:

Number of commands in the command block.

classmethod parse(data)#

Parse command from bytes array into CmdErase object.

Extracts header information and validates the command tag. Decodes device ID and group ID from header flags to determine memory ID for the erase operation.

Parameters:

data (bytes) – Input data as bytes containing the command structure

Raises:

SPSDKError – If incorrect header tag for erase command

Return type:

Self

Returns:

CmdErase object with parsed address, count, flags and memory ID

class spsdk.sbfile.sb2.commands.CmdFill(address, pattern, length=None, zero_filling=False)#

Bases: CmdBaseClass

SB2 Fill command for memory initialization operations.

This command fills a specified memory range with a given pattern, supporting various data patterns and lengths. The fill operation ensures proper alignment and handles pattern conversion for secure boot file generation.

Variables:

PADDING_VALUE – Default padding value used for alignment operations.

Initialize Command Fill.

Creates a fill command that writes a pattern to a specified memory address. The pattern is replicated to fill the specified length of memory. The pattern must be 1, 2, or 4 bytes long and will be automatically replicated to create a 4-byte pattern for efficient memory filling.

Parameters:
  • address (int) – Memory address where data should be written.

  • pattern (int) – Data pattern to be written (integer value).

  • length (Optional[int]) – Length of memory range to fill in bytes, defaults to 4.

  • zero_filling (bool) – Flag indicating if this is zero filling operation.

Raises:

SPSDKError – Length is not aligned to 4 bytes or pattern size invalid.

PADDING_VALUE = 0#
property address: int#

Get address of the command Fill.

Returns:

Address value of the Fill command.

export()#

Export command in binary form with proper alignment.

The method serializes the command to binary format and applies block alignment using either zero filling or random filling based on the zero_filling flag.

Return type:

bytes

Returns:

Serialized command data with proper block alignment.

classmethod parse(data)#

Parse command from bytes.

Parses the binary data to create a Fill command object by extracting and validating the command header information.

Parameters:

data (bytes) – Input data as bytes containing the command structure

Return type:

Self

Returns:

Command Fill object

Raises:

SPSDKError – If incorrect header tag

property pattern: bytes#

Return binary data pattern used for filling.

Returns:

Binary data pattern as bytes.

property raw_size: int#

Calculate raw size of the command header.

The method calculates the total size including the pattern length minus 4 bytes, with padding to align to CmdHeader.SIZE boundary.

Returns:

Raw size of the header in bytes.

class spsdk.sbfile.sb2.commands.CmdHeader(tag, flags=0, zero_filling=False)#

Bases: BaseClass

SBFile command header for SB2 format.

This class represents a command header structure used in SB2 (Secure Binary) files, providing functionality to create, validate, and export command headers with proper CRC calculation and binary formatting.

Variables:
  • FORMAT – Binary format string for struct packing/unpacking.

  • SIZE – Size of the header structure in bytes.

Initialize SB2 command header with specified parameters.

Creates a new command header instance with the given tag and optional flags. Initializes all header fields to default values and validates the command tag.

Parameters:
  • tag (int) – Command tag identifier from EnumCmdTag enumeration

  • flags (int) – Optional command flags, defaults to 0

  • zero_filling (bool) – Enable zero filling for the command, defaults to False

Raises:

SPSDKError – Invalid command tag not found in EnumCmdTag

FORMAT = '<2BH3L'#
SIZE = 16#
property crc: int#

Calculate CRC for the header data.

Computes a checksum using a custom algorithm that starts with 0x5A and adds each byte from the raw data (excluding the first byte) with overflow handling to maintain 8-bit values.

Returns:

Calculated CRC checksum as an 8-bit integer value.

export()#

Export command header as bytes.

Serializes the command header data including CRC into a byte representation suitable for transmission or storage.

Return type:

bytes

Returns:

Raw byte data of the command header with CRC.

classmethod parse(data)#

Parse command header from bytes array.

The method unpacks binary data into a CMDHeader object and validates the CRC checksum to ensure data integrity.

Parameters:

data (bytes) – Input binary data containing the command header.

Return type:

Self

Returns:

Parsed CMDHeader object with populated fields.

Raises:
  • SPSDKError – Raised when input data size is insufficient.

  • SPSDKError – Raised when CRC checksum validation fails.

class spsdk.sbfile.sb2.commands.CmdJump(address=0, argument=0, spreg=None)#

Bases: CmdBaseClass

SB2 Jump command for transferring execution control.

This command represents a jump instruction in SB2 (Secure Binary) files that transfers program execution to a specified memory address. It supports optional stack pointer configuration and can carry additional arguments for the target execution context.

Initialize Command Jump.

Parameters:
  • address (int) – Jump target address, defaults to 0.

  • argument (int) – Additional argument for jump command, defaults to 0.

  • spreg (Optional[int]) – Optional stack pointer register value.

property address: int#

Get the address of the Jump command.

Returns:

Address value of the Jump command.

property argument: int#

Get command’s argument value.

Returns:

The argument value stored in the command header.

classmethod parse(data)#

Parse command from bytes.

Parses the input byte data to create a Jump command object by extracting and validating the command header information.

Parameters:

data (bytes) – Input data as bytes containing the command structure.

Return type:

Self

Returns:

Command Jump object created from parsed data.

Raises:

SPSDKError – If incorrect header tag is found in the data.

property spreg: int | None#

Return command’s Stack Pointer.

The Stack Pointer value is only available when the command header flags field is set to 2, indicating that the count field contains the stack pointer value.

Returns:

Stack pointer value if flags equals 2, None otherwise.

class spsdk.sbfile.sb2.commands.CmdKeyStoreBackup(address, controller_id)#

Bases: CmdKeyStoreBackupRestore

SB2 command for backing up keystore data from non-volatile memory.

This command handles the backup operation of keystore information stored in the device’s non-volatile memory, allowing for secure retrieval and storage of cryptographic keys and certificates.

Initialize CmdKeyStoreBackupRestore.

Parameters:
  • address (int) – Address where to backup key-store or source for restoring key-store.

  • controller_id (ExtMemId) – ID of the memory to backup key-store or source memory to load key-store back.

Raises:
classmethod cmd_id()#

Return command ID for backup operation.

Return type:

EnumCmdTag

Returns:

Command tag enumeration value for write keystore from non-volatile memory operation.

class spsdk.sbfile.sb2.commands.CmdKeyStoreBackupRestore(address, controller_id)#

Bases: CmdBaseClass

SB2 Key Store Backup and Restore Command.

Abstract base class for implementing key store backup and restore operations in SB2 files. Provides shared functionality for managing memory controller identification and address handling for key store operations.

Variables:
  • ROM_MEM_DEVICE_ID_MASK – Bit mask for extracting controller ID from flags.

  • ROM_MEM_DEVICE_ID_SHIFT – Bit shift value for controller ID positioning.

Initialize CmdKeyStoreBackupRestore.

Parameters:
  • address (int) – Address where to backup key-store or source for restoring key-store.

  • controller_id (ExtMemId) – ID of the memory to backup key-store or source memory to load key-store back.

Raises:
ROM_MEM_DEVICE_ID_MASK = 65280#
ROM_MEM_DEVICE_ID_SHIFT = 8#
property address: int#

Return address where to backup key-store or source for restoring key-store.

Returns:

Address value from the header.

abstract classmethod cmd_id()#

Return command ID for the SB2 command.

This is an abstract method that must be implemented by derived command classes to provide their specific command identifier.

Return type:

EnumCmdTag

Returns:

Command tag enumeration value.

Raises:

NotImplementedError – Derived class has to implement this method.

property controller_id: int#

Get controller ID of the memory device.

Extracts the controller ID from the header flags that identifies the memory device used to backup key-store or source memory to load key-store back.

Returns:

Controller ID extracted from the ROM memory device ID mask.

classmethod parse(data)#

Parse command from bytes array into CmdKeyStoreBackupRestore object.

The method extracts header information, validates the command tag, and constructs the command object with parsed address and controller ID parameters.

Parameters:

data (bytes) – Input data as bytes array containing the command structure

Return type:

Self

Returns:

CmdKeyStoreBackupRestore object with parsed parameters

Raises:

SPSDKError – When there is invalid header tag

class spsdk.sbfile.sb2.commands.CmdKeyStoreRestore(address, controller_id)#

Bases: CmdKeyStoreBackupRestore

SB2 command for restoring keystore data into non-volatile memory.

This command handles the restoration of previously backed up keystore data from memory back into the device’s non-volatile storage, completing the keystore recovery process.

Initialize CmdKeyStoreBackupRestore.

Parameters:
  • address (int) – Address where to backup key-store or source for restoring key-store.

  • controller_id (ExtMemId) – ID of the memory to backup key-store or source memory to load key-store back.

Raises:
classmethod cmd_id()#

Return command ID for restore operation.

Return type:

EnumCmdTag

Returns:

Command tag enumeration value for write keystore to non-volatile memory operation.

class spsdk.sbfile.sb2.commands.CmdLoad(address, data, mem_id=0, zero_filling=False)#

Bases: CmdBaseClass

SB2 Load Command for memory data operations.

This command class represents a load operation that stores data into target processor memory at a specified address. It handles memory addressing, data alignment, and provides functionality for exporting and parsing load commands in SB2 format.

Initialize CMD Load command.

Creates a new Load command that writes data to a specified memory address. The command supports different memory interfaces through mem_id parameter and can be configured for zero filling behavior.

Parameters:
  • address (int) – Target memory address where data will be written.

  • data (bytes) – Binary data to be loaded into memory.

  • mem_id (int) – Memory interface identifier, defaults to 0.

  • zero_filling (bool) – Enable zero filling for unaligned data, defaults to False.

property address: int#

Return address in target processor to load data.

Returns:

Address value where data should be loaded in target processor memory.

export()#

Export command as binary data.

Updates internal data before exporting the command and appends the command’s data to the base export result.

Return type:

bytes

Returns:

Binary representation of the command including its data.

property flags: int#

Return command’s flag.

Returns:

Command flags as integer value.

classmethod parse(data)#

Parse command from bytes.

This method parses a LOAD command from binary data by extracting and validating the command header, verifying CRC integrity, and reconstructing the command object with proper memory identification.

Parameters:

data (bytes) – Input data as bytes containing the command structure.

Return type:

Self

Returns:

CMD Load object parsed from the input data.

Raises:
  • SPSDKError – Raised when there is invalid CRC in the command header.

  • SPSDKError – When there is incorrect header tag (not LOAD command).

property raw_size: int#

Calculate aligned size of the command including header and data.

The method calculates the total size by adding the header size and data length, then aligns the result to the nearest multiple of header size for proper memory alignment.

Returns:

Aligned size in bytes including command header and data payload.

class spsdk.sbfile.sb2.commands.CmdMemEnable(address, size, mem_id)#

Bases: CmdBaseClass

SB2 command to enable and configure memory initialization.

This command configures memory devices by specifying the source address of configuration data, the size of that data, and the target memory identifier. It manages memory device and group identification through flag manipulation.

Initialize CmdMemEnable command.

This command enables and configures memory using the provided configuration data. The method extracts device and group IDs from the memory ID and sets appropriate flags for memory initialization.

Parameters:
  • address (int) – Source address with configuration data for memory initialization.

  • size (int) – Size of configuration data used for memory initialization.

  • mem_id (int) – Identification of memory containing device and group information.

property address: int#

Return command’s address.

Returns:

The address value stored in the command header.

property flags: int#

Return command’s flag.

Returns:

Command flags as integer value.

classmethod parse(data)#

Parse Memory Enable command from binary data.

This method extracts device ID and group ID from the command header flags and constructs a Memory Enable command object with the parsed parameters.

Parameters:

data (bytes) – Binary data containing the Memory Enable command structure.

Raises:

SPSDKError – If the header tag is not MEM_ENABLE.

Return type:

Self

Returns:

Parsed Memory Enable command object.

property size: int#

Return command’s size in bytes.

Returns:

Size of the command including header.

class spsdk.sbfile.sb2.commands.CmdNop#

Bases: CmdBaseClass

SB2 No Operation command implementation.

This class represents a NOP (No Operation) command in the SB2 file format, which serves as a placeholder or padding command that performs no actual operation when executed by the target device.

Initialize Command Nop.

Creates a new NOP (No Operation) command instance that performs no action when executed. This command is typically used as a placeholder or for timing purposes in command sequences.

classmethod parse(data)#

Parse command from bytes array into CMD Nop object.

This method validates the command header tag and creates a new CMD Nop instance if the header contains the correct NOP tag.

Parameters:

data (bytes) – Input data as bytes array containing the command structure

Return type:

Self

Returns:

CMD Nop object instance

Raises:

SPSDKError – When there is incorrect header tag

class spsdk.sbfile.sb2.commands.CmdProg(address, mem_id, data_word1, data_word2=0, flags=0)#

Bases: CmdBaseClass

SB2.1 Program command for writing data to target memory.

This command handles programming operations in SB2.1 secure boot files, allowing data to be written to specific memory addresses on the target processor. It manages the target address, command flags, and associated data words for the programming operation.

Initialize CMD Prog command.

Creates a new program command for writing data to memory with specified address, memory ID, and data words. Supports both 4-byte and 8-byte data operations.

Parameters:
  • address (int) – Target memory address for programming operation.

  • mem_id (int) – Memory device identifier (0-255).

  • data_word1 (int) – First 32-bit data word to program.

  • data_word2 (int) – Second 32-bit data word for 8-byte operations, defaults to 0.

  • flags (int) – Additional command flags, defaults to 0.

Raises:

SPSDKError – Invalid memory ID (must be 0-255).

property address: int#

Return address in target processor to program data.

Returns:

Address value for programming data in target processor.

property data_word1: int#

Return data word 1.

Get the count value from the header which represents the first data word in the command structure.

Returns:

The count value from the header as data word 1.

property data_word2: int#

Return data word 2.

Returns:

The value of data word 2 from the header.

property flags: int#

Return command’s flags value.

Returns:

The flags value from the command header.

classmethod parse(data)#

Parse command from bytes.

The method parses the input byte data to create a command object by extracting header information and validating the command tag.

Parameters:

data (bytes) – Input data as bytes to be parsed into command object.

Raises:

SPSDKError – If incorrect header tag is found in the data.

Return type:

Self

Returns:

Parsed command object instance.

class spsdk.sbfile.sb2.commands.CmdReset#

Bases: CmdBaseClass

SB2 Reset command implementation.

This class represents a reset command in the SB2 (Secure Binary 2) file format, which instructs the target device to perform a system reset operation.

Initialize Command Reset.

Initializes a new Reset command instance by calling the parent constructor with the RESET command tag.

classmethod parse(data)#

Parse command from bytes array.

Parses the binary data to create a Reset command object by first validating the command header tag matches the expected RESET tag.

Parameters:

data (bytes) – Input data as bytes array containing the command structure.

Raises:

SPSDKError – If incorrect header tag found in the data.

Return type:

Self

Returns:

Cmd Reset object instance.

class spsdk.sbfile.sb2.commands.CmdTag#

Bases: CmdBaseClass

Command TAG class for SB file operations.

This class represents a TAG command used in Secure Binary (SB) files and serves as a header for boot sections in SB file version 1.x. It provides functionality for creating and parsing TAG commands within the SB file structure.

Initialize Command Tag.

Initialize a new Command Tag instance by calling the parent constructor with the TAG enumeration value.

classmethod parse(data)#

Parse command from bytes array.

Parses the binary data to create a command instance by extracting and validating the command header information.

Parameters:

data (bytes) – Input data as bytes array containing command information.

Raises:

SPSDKError – When there is incorrect header tag.

Return type:

Self

Returns:

Parsed command instance.

class spsdk.sbfile.sb2.commands.CmdVersionCheck(ver_type, version)#

Bases: CmdBaseClass

SB2 firmware version check command.

Represents a command that validates the version of secure or non-secure firmware during the secure boot process. The command fails if the actual firmware version is less than the expected minimum version, providing version control and security enforcement capabilities.

Initialize CmdVersionCheck command.

Parameters:
  • ver_type (VersionCheckType) – Version check type, see VersionCheckType enum.

  • version (int) – Version value to be checked.

Raises:

SPSDKError – If invalid version check type.

classmethod parse(data)#

Parse command from bytes array into command object.

Parses the binary data to extract command header information and creates a firmware version check command instance with the appropriate version type and version number.

Parameters:

data (bytes) – Input binary data containing the command structure

Raises:

SPSDKError – If incorrect header tag is found in the data

Return type:

Self

Returns:

Parsed firmware version check command object

property type: VersionCheckType#

Get type of the version check.

Returns the type of version check operation based on the header address using VersionCheckType enumeration.

Returns:

Type of the version check operation.

property version: int#

Return minimal version expected.

Returns:

Minimal version value from header count.

class spsdk.sbfile.sb2.commands.EnumCmdTag(tag, label, description=None)#

Bases: SpsdkEnum

SB2 command tag enumeration.

This enumeration defines all supported command tags used in SB2 (Secure Binary 2) files for bootloader operations including memory management, execution control, and security functions.

CALL = (5, 'CALL')#
ERASE = (7, 'ERASE')#
FILL = (3, 'FILL')#
FW_VERSION_CHECK = (11, 'FW_VERSION_CHECK', 'Check FW version fuse value')#
JUMP = (4, 'JUMP')#
LOAD = (2, 'LOAD')#
MEM_ENABLE = (9, 'MEM_ENABLE')#
NOP = (0, 'NOP')#
PROG = (10, 'PROG')#
RESET = (8, 'RESET')#
TAG = (1, 'TAG')#
WR_KEYSTORE_FROM_NV = (13, 'WR_KEYSTORE_FROM_NV', 'Backup key-store from non-volatile memory')#
WR_KEYSTORE_TO_NV = (12, 'WR_KEYSTORE_TO_NV', 'Restore key-store restore to non-volatile memory')#
class spsdk.sbfile.sb2.commands.EnumSectionFlag(tag, label, description=None)#

Bases: SpsdkEnum

SB2 section flags enumeration.

Defines the available flags that can be applied to sections in SB2 (Secure Binary version 2) files, including bootable sections, cleartext sections, and section termination markers.

BOOTABLE = (1, 'BOOTABLE')#
CLEARTEXT = (2, 'CLEARTEXT')#
LAST_SECT = (32768, 'LAST_SECT')#
class spsdk.sbfile.sb2.commands.VersionCheckType(tag, label, description=None)#

Bases: SpsdkEnum

Version check type enumeration for SB2 commands.

Defines the types of firmware version checking that can be performed, distinguishing between secure and non-secure firmware validation.

NON_SECURE_VERSION = (1, 'NON_SECURE_VERSION')#
SECURE_VERSION = (0, 'SECURE_VERSION')#
spsdk.sbfile.sb2.commands.get_device_id(mem_id)#

Get device ID from memory ID.

Extracts the device identifier from the given memory ID by applying a device ID mask and performing bit shifting operation.

Parameters:

mem_id (int) – Memory identifier value to extract device ID from.

Return type:

int

Returns:

Extracted device identifier.

spsdk.sbfile.sb2.commands.get_group_id(mem_id)#

Get group ID from memory ID.

Extracts the group identifier from a memory ID using bitwise operations with GROUP_ID_MASK and GROUP_ID_SHIFT constants.

Parameters:

mem_id (int) – Memory identifier to extract group ID from.

Return type:

int

Returns:

Extracted group identifier.

spsdk.sbfile.sb2.commands.get_memory_id(device_id, group_id)#

Get memory ID from device ID and group ID.

Combines device ID and group ID using bit shifting and masking operations to create a unique memory identifier for SB2 commands.

Parameters:
  • device_id (int) – Device identifier value.

  • group_id (int) – Group identifier value.

Return type:

int

Returns:

Combined memory ID created from device and group identifiers.

spsdk.sbfile.sb2.commands.parse_command(data)#

Parse SB 2.x command from bytes.

The method parses binary data representing an SB 2.x command and returns the appropriate command object based on the command tag found in the header.

Parameters:

data (bytes) – Input data as bytes containing the SB 2.x command.

Return type:

CmdBaseClass

Returns:

Parsed command object instance.

Raises:

SPSDKError – Raised when there is unsupported command provided.

SBFile Version 2 headers#

SPSDK SB2 image header management utilities.

This module provides functionality for handling Secure Binary version 2 (SB2) image headers, including header creation, validation, and serialization for NXP MCU secure provisioning.

class spsdk.sbfile.sb2.headers.ImageHeaderV2(version='2.0', product_version='1.0.0', component_version='1.0.0', build_number=0, flags=8, nonce=None, timestamp=None, padding=None)#

Bases: BaseClass

SB2 Image Header Version 2 implementation.

This class represents the header structure for Secure Binary version 2 image files, managing metadata including version information, build details, cryptographic nonce, and structural pointers for boot image processing.

Variables:
  • FORMAT – Binary format string for header serialization.

  • SIZE – Total size of the header structure in bytes.

  • SIGNATURE1 – Primary signature identifier ‘STMP’.

  • SIGNATURE2 – Secondary signature identifier ‘sgtl’.

Initialize Image Header Version 2.x.

Creates a new SB2 image header with specified version information, security parameters, and optional testing configurations.

Parameters:
  • version (str) – The image version value (default: 2.0)

  • product_version (str) – The product version (default: 1.0.0)

  • component_version (str) – The component version (default: 1.0.0)

  • build_number (int) – The build number value (default: 0)

  • flags (int) – The flags value (default: 0x08)

  • nonce (Optional[bytes]) – The NONCE value for cryptographic operations

  • timestamp (Optional[datetime]) – Timestamp for the header; None to use current time

  • padding (Optional[bytes]) – Header padding (8 bytes) for testing; None to use random values

FORMAT = '<16s4s4s2BH4I4H4sQ12HI4s'#
SIGNATURE1 = b'STMP'#
SIGNATURE2 = b'sgtl'#
SIZE = 96#
export(padding=None)#

Export SB2 header object into binary format.

The method serializes all header fields including nonce, version information, flags, and various block offsets into a packed binary representation suitable for SB2 file format.

Parameters:

padding (Optional[bytes]) – Header padding 8 bytes for testing purposes; None to use random value

Return type:

bytes

Returns:

Binary representation of the SB2 header

Raises:
  • SPSDKError – When nonce format is incorrect

  • SPSDKError – When padding length is not 8 bytes

  • SPSDKError – When resulting header length is incorrect

flags_desc()#

Get flag description based on current flags value.

Returns a human-readable description indicating whether the flags represent a signed or unsigned state.

Return type:

str

Returns:

“Signed” if flags equals 0x8, otherwise “Unsigned”.

classmethod parse(data)#

Parse SB2 header from binary data.

Deserializes the SB2 header structure from its binary representation, validating signatures and extracting all header fields including version information, flags, and various block offsets.

Parameters:

data (bytes) – Binary data containing the SB2 header structure.

Return type:

Self

Returns:

Parsed instance of the SB2 header.

Raises:

SPSDKError – If data is insufficient or header signatures don’t match.

SBFile Version 2 images#

SPSDK SB2 boot image generation and management utilities.

This module provides functionality for creating and managing Secure Binary version 2.0 and 2.1 boot images, including advanced parameter configuration and image processing capabilities for NXP MCU secure provisioning.

class spsdk.sbfile.sb2.images.BootImageV20(signed, kek, *sections, product_version='1.0.0', component_version='1.0.0', build_number=0, advanced_params=<spsdk.sbfile.sb2.images.SBV2xAdvancedParams object>)#

Bases: BaseClass

Secure Binary Image V2.0 container for NXP MCU secure provisioning.

This class manages the creation and manipulation of Secure Binary (SB) version 2.0 image files, including encryption, signing, and section management for secure firmware deployment on NXP microcontrollers.

Variables:
  • HEADER_MAC_SIZE – Size of the MAC key in bytes (32).

  • DEK_MAC_SIZE – Size of AES encrypted DEK and MAC including padding (80).

  • KEY_BLOB_SIZE – Size of the key blob structure (80).

Initialize Secure Binary Image V2.0.

Creates a new instance of Secure Binary Image version 2.0 with specified configuration parameters and boot sections.

Parameters:
  • signed (bool) – True if image is signed, False otherwise

  • kek (bytes) – Key for wrapping DEK and MAC keys

  • sections (BootSectionV2) – Boot sections to be included in the image

  • product_version (str) – The product version (default: 1.0.0)

  • component_version (str) – The component version (default: 1.0.0)

  • build_number (int) – The build number value (default: 0)

  • advanced_params (SBV2xAdvancedParams) – Advanced parameters for encryption of the SB file, use for tests only

Raises:

SPSDKError – Invalid dek or mac

DEK_MAC_SIZE = 80#
HEADER_MAC_SIZE = 32#
KEY_BLOB_SIZE = 80#
add_boot_section(section)#

Add new Boot section into image.

Parameters:

section (BootSectionV2) – Boot section to be added to the image

Raises:
  • SPSDKError – Raised when section is not instance of BootSectionV2 class

  • SPSDKError – Raised when boot section has duplicate UID

Return type:

None

property cert_block: CertBlockV1 | None#

Get certificate block from the SB file.

The method retrieves the certificate block from the certificate section if the SB file is signed and the block has been assigned.

Returns:

Certificate block if available, None if SB file is not signed or block is not assigned yet.

property cert_header_size: int#

Calculate the raw size (not aligned) for certificate header.

The size includes the image header, MAC, key blob, and all boot sections.

Returns:

Total raw size in bytes for the certificate header.

property dek: bytes#

Get data encryption key.

Returns:

Data encryption key as bytes.

export(padding=None)#

Export image object to binary format.

The method serializes the complete SB2 image including header, certificates, boot sections, and signature into a binary representation ready for deployment.

Parameters:

padding (Optional[bytes]) – Header padding (8 bytes) for testing purpose; None to use random values (recommended)

Return type:

bytes

Returns:

Exported bytes representing the complete SB2 image

Raises:
  • SPSDKError – No boot sections available

  • SPSDKError – Invalid DEK or MAC key length (must be 32 bytes each)

  • SPSDKError – Certificate section required for signed images

  • SPSDKError – Signature provider not assigned for signed image

  • SPSDKError – Certificate block not assigned for signed image

  • SPSDKError – Header nonce is missing

  • SPSDKError – Invalid length of exported data

property header: ImageHeaderV2#

Get image header.

Returns:

Image header containing metadata and configuration information.

property kek: bytes#

Return key for wrapping DEK and MAC keys.

Returns:

KEK (Key Encryption Key) used for wrapping DEK and MAC keys.

property mac: bytes#

Get message authentication code.

Returns:

Message authentication code as bytes.

classmethod parse(data, kek=b'')#

Parse SB2.x image from raw bytes data.

This method parses a Secure Binary 2.x image from binary data, validates the header MAC, decrypts the content using the provided KEK, and reconstructs the image object with all its sections including certificate and boot sections.

Parameters:
  • data (bytes) – Raw binary data containing the SB2.x image to be parsed

  • kek (bytes) – Key Encryption Key for unwrapping DEK and MAC keys (required for decryption)

Return type:

Self

Returns:

Parsed SB2.x image object with all sections loaded

Raises:
  • SPSDKError – Invalid or corrupted header format

  • SPSDKError – Unsupported header version (not 2.0)

  • SPSDKError – Header MAC validation failed

  • SPSDKError – KEK parameter is empty or not provided

  • SPSDKError – Header nonce field is missing

  • SPSDKError – Certificate section signature verification failed

property raw_size: int#

Get the total raw size of the image including signature if present.

The method calculates the complete raw size by adding the signature size to the base raw size when the image is signed.

Raises:

SPSDKError – Certificate block not present for signed image.

Returns:

Total raw size of the image in bytes.

property raw_size_without_signature: int#

Return image raw size without signature, used to calculate image blocks.

The method calculates the total size including header, HMAC, key blob, certificates section (if signed), and all boot sections.

Raises:

SPSDKError – When certification block is not present for signed image.

Returns:

Total raw size in bytes without signature.

property signed: bool#

Check whether SB file is signed and encrypted or only encrypted.

Returns:

True if the SB file is signed and encrypted, False if only encrypted.

update()#

Update boot image header and internal structures.

This method recalculates and updates various header fields including boot section IDs, block sizes, offsets, and MAC counts. It also updates certificate block headers if present and sets appropriate flags based on whether the image is signed.

Return type:

None

class spsdk.sbfile.sb2.images.BootImageV21(kek, *sections, product_version='1.0.0', component_version='1.0.0', build_number=0, advanced_params=<spsdk.sbfile.sb2.images.SBV2xAdvancedParams object>, flags=32776)#

Bases: BaseClass

Secure Binary Image V2.1 container for NXP MCU secure provisioning.

This class represents a Secure Binary Image version 2.1 that encapsulates boot sections with encryption and authentication capabilities. It manages the image header, cryptographic keys, and provides functionality for creating signed and encrypted boot images.

Variables:
  • HEADER_MAC_SIZE – Size of the header MAC in bytes (32).

  • KEY_BLOB_SIZE – Size of the key blob in bytes (80).

  • SHA_256_SIZE – Size of SHA-256 hash in bytes (32).

  • FLAGS_SHA_PRESENT_BIT – Flag indicating SHA-256 presence (0x8000).

  • FLAGS_ENCRYPTED_SIGNED_BIT – Flag for signed and encrypted image (0x0008).

Initialize Secure Binary Image V2.1.

Creates a new Secure Binary Image V2.1 instance with the specified encryption key and configuration parameters. The image can contain multiple boot sections that will be processed during secure boot.

Parameters:
  • kek (bytes) – Key encryption key used to wrap DEK and MAC keys.

  • sections (BootSectionV2) – Variable number of boot sections to include in the image.

  • product_version (str) – Product version string in format “x.y.z”.

  • component_version (str) – Component version string in format “x.y.z”.

  • build_number (int) – Build number for the image.

  • advanced_params (SBV2xAdvancedParams) – Advanced encryption parameters including DEK, MAC, nonce, and timestamp.

  • flags (int) – Image flags controlling SHA presence and encryption/signing behavior.

FLAGS_ENCRYPTED_SIGNED_BIT = 8#
FLAGS_SHA_PRESENT_BIT = 32768#
HEADER_MAC_SIZE = 32#
KEY_BLOB_SIZE = 80#
SHA_256_SIZE = 32#
add_boot_section(section)#

Add new Boot section into image.

Parameters:

section (BootSectionV2) – Boot section to be added

Raises:

SPSDKError – Raised when section is not instance of BootSectionV2 class

Return type:

None

property cert_block: CertBlockV1 | None#

Get certificate block from SB file.

Returns the certificate block if the SB file is signed and the block has been assigned, otherwise returns None.

Returns:

Certificate block instance or None if not available.

property cert_header_size: int#

Calculate the raw size of the certificate header section.

The method computes the total size including the image header, MAC, key blob, and certificate block if present. The size is not aligned to any boundary.

Returns:

Raw size in bytes of the certificate header section.

property dek: bytes#

Get the data encryption key.

Returns:

Data encryption key as bytes.

export(padding=None)#

Export SB2 image to binary format.

The method validates all required components, updates internal structures, and exports the complete SB2 image including header, certificates, boot sections, and signature.

Parameters:

padding (Optional[bytes]) – Header padding (8 bytes) for testing purpose; None to use random values

Return type:

bytes

Returns:

Complete SB2 image as binary data

Raises:
classmethod get_advanced_params(config)#

Get advanced parameters from configuration.

Extracts and processes advanced SB 2.x parameters including timestamp, DEK, MAC, nonce, and zero padding settings from the provided configuration dictionary.

Parameters:

config (dict[str, Any]) – Configuration dictionary containing advanced parameter settings.

Return type:

SBV2xAdvancedParams

Returns:

Advanced parameters object for SB 2.x file generation.

classmethod get_commands_validation_schemas(family=None)#

Create the list of validation schemas for SB2.1 commands.

The method retrieves the base SB2.1 schema and optionally filters commands based on the specified device family. When a family is provided, only commands supported by that family are included in the validation schema.

Parameters:

family (Optional[FamilyRevision]) – Device family filter, if None all commands are returned.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas for SB2.1 commands.

classmethod get_config_template(family)#

Generate configuration template for Secure Binary v2.1.

Creates a configuration template with validation schemas for the specified device family. The template includes all necessary configuration options and their descriptions.

Parameters:

family (FamilyRevision) – Device family revision to generate template for.

Return type:

str

Returns:

Configuration template as a string with comments and validation schemas.

static get_supported_families()#

Get supported families for SB2.1 format.

This method retrieves all device families that support the SB2.1 secure boot file format from the database manager.

Return type:

list[FamilyRevision]

Returns:

List of supported family revisions for SB2.1 format.

classmethod get_validation_schemas(family)#

Create the list of validation schemas for SB2 image configuration.

The method builds a comprehensive list of validation schemas by combining family-specific schemas, MBI schemas, SB2 schemas, and optionally keyblob schemas based on device family capabilities.

Parameters:

family (FamilyRevision) – Device family revision to get validation schemas for.

Return type:

list[dict[str, Any]]

Returns:

List of validation schema dictionaries for configuration validation.

property header: ImageHeaderV2#

Get image header.

Returns:

Image header containing metadata and configuration information.

property kek: bytes#

Return key to wrap DEC and MAC keys.

Returns:

Key encryption key as bytes.

classmethod load_from_config(config, key_file_path=None, signature_provider=None, signing_certificate_file_paths=None, root_key_certificate_paths=None, rkth_out_path=None)#

Create an instance of BootImageV21 from configuration.

This method constructs a Secure Binary V2.1 image by parsing the provided configuration, setting up certificate blocks, loading encryption keys, processing sections and commands, and configuring signature providers. It also handles root key hash generation and output.

Parameters:
  • config (Config) – Input standard configuration containing image settings and sections.

  • key_file_path (Optional[str]) – Path to key file for SB-KEK encryption key.

  • signature_provider (Optional[SignatureProvider]) – Signature provider instance to sign the final image.

  • signing_certificate_file_paths (Optional[list[str]]) – List of paths to signing certificate chain files.

  • root_key_certificate_paths (Optional[list[str]]) – List of paths to root key certificate files for verifying other certificates. Maximum 4 certificates allowed, extras ignored. One certificate must match the first in signing_certificate_file_paths.

  • rkth_out_path (Optional[str]) – Output path for root key hash table file. If None, uses ‘hash.bin’ in working directory or config-specified path.

Return type:

Self

Returns:

Configured BootImageV21 instance ready for image generation.

property mac: bytes#

Get the message authentication code.

Returns:

Message authentication code as bytes.

classmethod parse(data, offset=0, kek=b'', plain_sections=False)#

Parse SB2.1 boot image from binary data.

This method parses a Secure Binary 2.1 image from raw bytes, verifying signatures, unwrapping encryption keys, and reconstructing the boot image structure with all its components including certificate blocks and boot sections.

Parameters:
  • data (bytes) – Raw binary data containing the SB2.1 image to parse

  • offset (int) – Starting offset within the data where parsing begins

  • kek (bytes) – Key Encryption Key used for unwrapping DEK and MAC keys

  • plain_sections (bool) – Whether sections are unencrypted (debug mode only, not ROM supported)

Return type:

BootImageV21

Returns:

Parsed BootImageV21 object with all components initialized

Raises:
  • SPSDKError – When KEK is empty or missing

  • SPSDKError – When header format is invalid or offset mismatch occurs

  • SPSDKError – When certificate block signature verification fails

  • SPSDKError – When header nonce is not present

  • SPSDKError – When bootable section SHA-256 verification fails

classmethod parse_sb21_config(config_path, external_files=None)#

Parse SB2.1 configuration file and create configuration object.

The method attempts to parse the configuration file as a BD (Boot Data) file first. If that fails, it falls back to parsing as a YAML configuration file with validation.

Parameters:
  • config_path (str) – Path to configuration file either BD or YAML formatted.

  • external_files (Optional[list[str]]) – Optional list of external files for BD processing.

Raises:
  • SPSDKError – Invalid BD file or configuration parsing error.

  • SPSDKValueError – Missing required options or family key in BD file.

Return type:

Config

Returns:

Parsed configuration object with family and revision information.

property raw_size: int#

Return image raw size (not aligned).

Calculates the total raw size of the image including header, HMAC, key blob, certificate block (if present with signature), and all boot sections.

Raises:

SPSDKError – If certificate block exists but is not signed.

Returns:

Total raw size in bytes of the image components.

property signed: bool#

Check if the SB file is signed.

SB2.1 format files are always signed by design.

Returns:

True as SB2.1 files are always signed.

update()#

Update the BootImageV21 internal structure and header fields.

This method recalculates and updates various header fields including boot section IDs, block sizes, offsets, and MAC counts. It also updates the certificate block header if present. The method ensures all internal structures are synchronized with the current state of boot sections and certificate blocks.

Raises:

SPSDKError – When certificate block exists but is not signed.

Return type:

None

static validate_header(binary)#

Validate SB2.1 header in binary data.

Parameters:

binary (bytes) – Binary data to be validated

Raises:

SPSDKError – Invalid header of SB2.1 data

Return type:

None

class spsdk.sbfile.sb2.images.SBV2xAdvancedParams(dek=None, mac=None, nonce=None, timestamp=None, padding=None)#

Bases: object

SBV2x Advanced Parameters Manager.

This class manages advanced encryption parameters for SB file generation including DEK/MAC keys, nonce, timestamp, and padding. Primarily used for testing scenarios where deterministic values are needed, while production usage typically relies on default random values and current timestamps.

Initialize SBV2xAdvancedParams.

Creates advanced parameters for SB2.x file generation with encryption keys, nonce, timestamp and padding. If parameters are not provided, secure random values or current timestamp will be used.

Parameters:
  • dek (Optional[bytes]) – DEK (Data Encryption Key) - must be 32 bytes if provided.

  • mac (Optional[bytes]) – MAC (Message Authentication Code) key - must be 32 bytes if provided.

  • nonce (Optional[bytes]) – Cryptographic nonce - must be 16 bytes if provided.

  • timestamp (Optional[datetime]) – Fixed timestamp for the header; use None to use current date/time.

  • padding (Optional[bytes]) – Header padding (8 bytes) for testing purpose; None to use random values (recommended).

Raises:
property dek: bytes#

Get DEK (Data Encryption Key).

Returns:

The DEK key as bytes.

property mac: bytes#

Get MAC key.

Returns:

MAC key as bytes.

property nonce: bytes#

Get the NONCE value.

Returns:

The NONCE as bytes.

property padding: bytes#

Get the padding bytes for the image.

Returns:

Padding bytes as a byte string.

property timestamp: datetime#

Get the timestamp of the SB2 image.

Returns:

Timestamp when the image was created.

property zero_padding: bool#

Check if the padding bytes are all zeros.

Returns:

True if padding consists of 8 zero bytes, False otherwise.

SBFile Version 2 sections#

SPSDK SB2 file sections implementation.

This module provides section classes for SB2 (Secure Binary version 2) file format, including boot sections and certificate sections with encryption and authentication capabilities.

class spsdk.sbfile.sb2.sections.BootSectionV2(uid, *commands, hmac_count=1, zero_filling=False)#

Bases: BaseClass

Boot Section V2 for Secure Binary file format.

This class represents a boot section in the SB2.x file format, managing commands, HMAC authentication data, and section metadata. It provides functionality for building bootable sections with cryptographic integrity protection.

Variables:

HMAC_SIZE – Size of HMAC in bytes (32).

Initialize BootSectionV2.

Parameters:
  • uid (int) – Section unique identification number.

  • commands (CmdBaseClass) – Variable number of command objects to include in the section.

  • hmac_count (int) – The number of HMAC entries, defaults to 1.

  • zero_filling (bool) – If True, the section will be zero-filled, defaults to False.

HMAC_SIZE = 32#
append(cmd)#

Add command to section.

Parameters:

cmd (CmdBaseClass) – Command object to be added to the section.

Raises:

AssertionError – If cmd is not an instance of CmdBaseClass.

Return type:

None

export(dek=b'', mac=b'', counter=None)#

Export Boot Section object to encrypted binary format.

The method encrypts the section header and commands using AES-CTR encryption, calculates HMAC for integrity protection, and returns the complete encrypted section data ready for secure boot file generation.

Parameters:
  • dek (bytes) – Data Encryption Key used for AES-CTR encryption of header and commands

  • mac (bytes) – Message Authentication Code key for HMAC calculation

  • counter (Optional[Counter]) – Counter object for AES-CTR mode encryption, gets incremented during process

Return type:

bytes

Returns:

Encrypted section data containing header, HMAC data, and encrypted commands

Raises:

SPSDKError – Invalid parameter types or missing commands in section

property hmac_count: int#

Calculate the number of HMACs required for the section.

The method determines the HMAC count based on the total raw size of all commands in the section. It calculates the number of 16-byte blocks needed and returns the minimum between the configured HMAC count and the actual block count.

Returns:

Number of HMACs required for this section.

property is_last: bool#

Check whether the section is the last one.

This method examines the section header flags to determine if the current section is marked as the last section in the sequence.

Returns:

True if this is the last section, False otherwise.

classmethod parse(data, offset=0, plain_sect=False, dek=b'', mac=b'', counter=None)#

Parse Boot Section from bytes.

Decrypts and parses a boot section from raw binary data, validating HMAC integrity and extracting commands. The method handles encrypted sections with proper counter management and HMAC verification.

Parameters:
  • data (bytes) – Raw binary data containing the boot section to parse.

  • offset (int) – Starting offset within the data buffer for parsing.

  • plain_sect (bool) – Whether sections are unencrypted (debugging only, not ROM supported).

  • dek (bytes) – Data Encryption Key as bytes for decryption.

  • mac (bytes) – Message Authentication Code as bytes for HMAC verification.

  • counter (Optional[Counter]) – Counter object for AES-CTR decryption state management.

Return type:

BootSectionV2

Returns:

Parsed BootSectionV2 object containing the extracted commands.

Raises:

SPSDKError – Invalid parameter types or HMAC verification failure.

property raw_size: int#

Get the raw size of the section in bytes.

Calculates the total size including command header, HMAC data, all commands, and padding to ensure 16-byte alignment.

Returns:

Total raw size of the section in bytes.

property uid: int#

Get Boot Section UID.

Returns:

The unique identifier of the boot section.

class spsdk.sbfile.sb2.sections.CertSectionV2(cert_block)#

Bases: BaseClass

SB2 Certificate Section V2 representation.

This class manages certificate sections in Secure Binary 2.0 files, handling certificate block data with proper HMAC validation and section formatting.

Variables:
  • HMAC_SIZE – Size of HMAC in bytes (32).

  • SECT_MARK – Section marker identifier for certificate sections.

Initialize certificate block section.

Creates a new certificate block section with proper header configuration including section flags and address marking.

Parameters:

cert_block (CertBlockV1) – Certificate block to be wrapped in this section.

Raises:

AssertionError – If cert_block is not an instance of CertBlockV1.

HMAC_SIZE = 32#
SECT_MARK = 1852270963#
property cert_block: CertBlockV1#

Get certification block.

Returns:

Certification block instance.

export(dek=b'', mac=b'', counter=None)#

Export Certificate Section object to binary format.

The method encrypts the header using AES-CTR, generates HMAC for authentication, and combines all components into the final binary representation.

Parameters:
  • dek (bytes) – Data Encryption Key in bytes format for AES-CTR encryption.

  • mac (bytes) – Message Authentication Code key in bytes for HMAC generation.

  • counter (Optional[Counter]) – Counter object used for AES-CTR encryption mode.

Return type:

bytes

Returns:

Binary representation of the certificate section.

Raises:
  • SPSDKError – Invalid parameter type for dek, mac, or counter.

  • SPSDKError – Exported data size doesn’t match expected raw size.

classmethod parse(data, offset=0, dek=b'', mac=b'', counter=None)#

Parse Certificate Section from bytes array.

Parses and validates an encrypted certificate section with HMAC verification, decrypts the header, and extracts the certificate block.

Parameters:
  • data (bytes) – Raw data of parsed image.

  • offset (int) – The offset of input data.

  • dek (bytes) – The DEK value in bytes (required).

  • mac (bytes) – The MAC value in bytes (required).

  • counter (Optional[Counter]) – The counter object (required).

Return type:

CertSectionV2

Returns:

Parsed cert section v2 object.

Raises:
  • SPSDKError – Raised when dek, mac, counter are not valid.

  • SPSDKError – Raised when there is invalid header HMAC, TAG, FLAGS, Mark.

  • SPSDKError – Raised when there is invalid certificate block HMAC.

property raw_size: int#

Calculate raw size of section in bytes.

The method calculates the total size including section header, HMAC values for both header and certificate block, and the certificate block itself.

Returns:

Total raw size of the section in bytes.

SBFile Version 3.1.#

SPSDK SB3.1 secure boot file format implementation.

This module provides comprehensive support for creating, parsing, and manipulating SB3.1 (Secure Binary version 3.1) files used in NXP MCU secure boot process. It includes command definitions, parsing utilities, and constants for the SB3.1 format.

class spsdk.sbfile.sb31.CmdCall(address)#

Bases: BaseCmd

Address will be the address to jump.

Initialize Command with specified address.

Parameters:

address (int) – Memory address where the command will be executed.

CMD_TAG = (4, 'call')#
cmd_tag = (4, 'call')#
get_config_context(data_path='./')#

Create configuration for the CALL command.

This method generates a configuration dictionary containing the command’s properties and settings, including the address to call. The CALL command executes code at a specified address but unlike EXECUTE, it returns control to the bootloader after completion.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Creates a list of command objects based on the provided configuration data.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKValueError – Invalid data format or corrupted command structure

Return type:

Self

Returns:

Parsed CmdCall command instance

class spsdk.sbfile.sb31.CmdConfigureMemory(address, memory_id=0)#

Bases: BaseCmd

SB3.1 command for configuring memory parameters.

This command sets up memory configuration parameters required before performing memory operations in the secure boot process. It specifies the target memory address and memory identifier for subsequent operations.

Variables:

CMD_TAG – Command tag identifier for CONFIGURE_MEMORY operations.

Initialize SB3.1 command with address and memory ID.

Parameters:
  • address (int) – Target address for the command operation.

  • memory_id (int) – Memory identifier, defaults to 0.

CMD_TAG = (11, 'configureMemory')#
export()#

Export command as bytes array.

Serializes the command into a binary format using the predefined FORMAT structure with TAG, memory_id, address, and CMD_TAG.tag fields.

Return type:

bytes

Returns:

Binary representation of the command.

get_config_context(data_path='./')#

Create configuration for the CONFIGURE_MEMORY command.

This method generates a configuration dictionary containing the command’s properties and settings, including the memory configuration address and memory ID. The CONFIGURE_MEMORY command sets up memory parameters required before performing operations on the specified memory.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Creates a list of command objects from the provided configuration data.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List containing a single command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Invalid data format or parsing failure

Return type:

Self

Returns:

CmdConfigureMemory instance created from parsed data

class spsdk.sbfile.sb31.CmdCopy(address, length, destination_address=0, memory_id_from=0, memory_id_to=0)#

Bases: BaseCmd

Copy data from one place to another.

Initialize SB3.1 copy command.

Creates a new copy command that transfers data from one memory location to another, potentially between different memory regions.

Parameters:
  • address (int) – Source memory address to copy data from.

  • length (int) – Number of bytes to copy from source address.

  • destination_address (int) – Target memory address where data will be copied to.

  • memory_id_from (int) – Source memory region identifier.

  • memory_id_to (int) – Target memory region identifier.

CMD_TAG = (8, 'copy')#
export()#

Export command as bytes array.

Serializes the command into a binary format suitable for transmission or storage. The exported data includes the base command data followed by destination address, source memory ID, target memory ID, and a reserved field.

Return type:

bytes

Returns:

Binary representation of the command.

property export_length: int#

Export length of command in bytes.

Calculates the total export length including the base header (16 bytes) and additional COPY command specific fields (16 bytes).

Returns:

Length of command in bytes.

get_config_context(data_path='./')#

Create configuration for the COPY command.

This method generates a configuration dictionary containing the command’s properties and settings, including source address, destination address, size, and memory IDs. The COPY command transfers data between different memory regions, which is useful for copying firmware or data from one memory location to another.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates a command object by extracting configuration parameters from the provided Config object and returns it as a single-item list.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Deserializes a CmdCopy command from its binary representation by extracting the header information and command-specific parameters.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command

Return type:

Self

Returns:

CmdCopy instance created from the parsed data

Raises:

SPSDKError – Invalid padding detected in the command data

class spsdk.sbfile.sb31.CmdErase(address, length, memory_id=0)#

Bases: BaseCmd

SB3.1 erase command for memory operations.

This command erases a specified address range in memory, with the erase operation automatically rounded up to the sector size. The command supports different memory types through memory ID specification.

Variables:

CMD_TAG – Command tag identifier for erase operations.

Initialize SB3.1 command with address, length and memory parameters.

Parameters:
  • address (int) – Target memory address for the command operation

  • length (int) – Number of bytes to be processed by the command

  • memory_id (int) – Identifier of the target memory interface, defaults to 0

CMD_TAG = (1, 'erase')#
export()#

Export command as bytes array.

Serializes the command into a binary format suitable for secure boot file generation. The exported data includes the base command data followed by memory ID and padding.

Return type:

bytes

Returns:

Binary representation of the command.

property export_length: int#

Get export length.

Calculate the total length of the exported command data, including the base command size and additional bytes for memory ID and padding.

Returns:

The length of the exported command data in bytes.

get_config_context(data_path='./')#

Create configuration for the ERASE command.

This method generates a configuration dictionary containing the command’s properties and settings, including memory address, length, and memory ID. The ERASE command erases a specified memory region, with the operation being rounded up to the sector size for the specified memory.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Creates command objects from configuration data including address, size, and memory ID.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

This method deserializes a CmdErase command from its binary representation, extracting the address, length, and memory ID while validating padding fields.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command

Return type:

Self

Returns:

CmdErase instance parsed from the input data

Raises:

SPSDKError – Invalid padding in the command data

class spsdk.sbfile.sb31.CmdExecute(address)#

Bases: BaseCmd

Address will be the jump-to address.

Initialize Command with specified address.

Parameters:

address (int) – Memory address where the command will be executed.

CMD_TAG = (3, 'execute')#
get_config_context(data_path='./')#

Create configuration for the EXECUTE command.

This method generates a configuration dictionary containing the command’s properties and settings, including the address to jump to for execution. The EXECUTE command triggers execution at a specified address, which is typically used to start running code after it has been loaded into memory.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Creates a list of command objects based on the provided configuration data.

Parameters:

config (Config) – Configuration object containing command fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Invalid data format or parsing error

Return type:

Self

Returns:

CmdExecute instance created from parsed data

class spsdk.sbfile.sb31.CmdFillMemory(address, length, pattern)#

Bases: BaseCmd

SB3.1 command for filling memory range with a specified pattern.

This command writes a repeating pattern to a contiguous block of memory, effectively initializing or clearing memory regions during secure boot operations.

Variables:

CMD_TAG – Command identifier for fill memory operations.

Initialize fill memory command.

Creates a command that fills a specified memory region with a given pattern.

Parameters:
  • address (int) – Target memory address to start filling

  • length (int) – Secure Binary bytes to fill in memory

  • pattern (int) – Fill pattern value to write to memory

CMD_TAG = (12, 'fillMemory')#
export()#

Export command as bytes array.

Serializes the command data including the pattern and padding into a binary format suitable for storage or transmission.

Return type:

bytes

Returns:

Binary representation of the command with pattern and padding.

property export_length: int#

Calculate the total export length including the command header and data.

Returns:

Total length in bytes of the exported command.

get_config_context(data_path='./')#

Create configuration for the FILL_MEMORY command.

This method generates a configuration dictionary containing the command’s properties and settings, including the starting address, size of the region to fill, and the pattern value to use for filling. The FILL_MEMORY command fills a specified memory region with a repeating pattern, which is useful for initializing memory areas or erasing sensitive data.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates a command object by extracting address, size, and pattern values from the provided configuration dictionary with default fallback values.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Deserializes a CmdErase command from its binary representation by extracting address, length, and pattern fields while validating padding bytes.

Parameters:

data (bytes) – Input data as bytes array

Return type:

Self

Returns:

CmdErase command instance

Raises:

SPSDKError – Invalid padding bytes detected

class spsdk.sbfile.sb31.CmdLoad(address, data, memory_id=0, compress=False)#

Bases: CmdLoadBase

Data to write follows the range header.

Initialize Load command with specified parameters.

Parameters:
  • address (int) – Target memory address where data will be loaded

  • data (bytes) – Binary data to be loaded into memory

  • memory_id (int) – Target memory identifier (default: 0)

  • compress (bool) – Enable data compression for the load operation (default: False)

CMD_TAG = (2, 'load')#
get_config_context(data_path='./')#

Create configuration for the LOAD command.

This method generates a configuration dictionary containing the command’s properties and settings, including address, memory ID, and data representation. The LOAD command writes data to a specified memory address, which is essential for programming firmware, configuration parameters, or other data into device memory.

Parameters:

data_path (str) – Path to store any data files that might be created for large data.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary and create command objects.

Creates one or more command objects based on the configuration. When compression is enabled, the data is split into sector-aligned chunks and multiple commands are created.

Parameters:

config (Config) – Configuration object with command fields including address, memoryId, data source, compression settings, and sector size.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

Raises:

SPSDKValueError – Address not aligned to sector size when compression is enabled.

class spsdk.sbfile.sb31.CmdLoadCmac(address, data, memory_id=0)#

Bases: CmdLoadBase

Load cmac. ROM is calculating cmac from loaded data.

Initialize Load command with target address and data.

Parameters:
  • address (int) – Target memory address where data will be loaded

  • data (bytes) – Binary data to be loaded into memory

  • memory_id (int) – Target memory identifier, defaults to 0

CMD_TAG = (7, 'loadCMAC')#
get_config_context(data_path='./')#

Create configuration for the LOAD_CMAC command.

This method generates a configuration dictionary containing the command’s properties and settings, including address, memory ID, and CMAC data. The CMAC data is stored in a separate binary file for better management.

Parameters:

data_path (str) – Path where the CMAC data file will be stored.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates command objects from configuration data including address, memory ID, and binary file data.

Parameters:

config (Config) – Configuration object with command fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

classmethod parse(data)#

Parse command from bytes array.

Extracts command data from a byte array and creates a command instance with the parsed address, data, and memory ID.

Parameters:

data (bytes) – Input data as bytes array

Return type:

Self

Returns:

Command instance

Raises:

SPSDKError – Invalid cmd_tag was found

class spsdk.sbfile.sb31.CmdLoadHashLocking(address, data, memory_id=0)#

Bases: CmdLoadBase

SB3.1 Load Hash Locking command for secure boot operations.

This command loads hash data to a specified memory address while enabling ROM-based hash calculation and locking mechanisms. It extends the base load functionality with additional security features including hash verification and memory protection.

Variables:

CMD_TAG – Command identifier for load hash locking operations.

Initialize Load command with target address and data.

Parameters:
  • address (int) – Target memory address where data will be loaded

  • data (bytes) – Binary data to be loaded into memory

  • memory_id (int) – Target memory identifier, defaults to 0

CMD_TAG = (9, 'loadHashLocking')#
export()#

Export command as bytes array.

Exports the command data by calling the parent class export method and appending 64 null bytes for padding or alignment purposes.

Return type:

bytes

Returns:

Command data as bytes with additional padding.

property export_length: int#

Export length of command.

Returns:

Length of command in bytes.

get_config_context(data_path='./')#

Create configuration for the LOAD_HASH_LOCKING command.

This method generates a configuration dictionary containing the command’s properties and settings, including address, memory ID, and hash data. The hash data is stored in a separate binary file for better management.

Parameters:

data_path (str) – Path where the hash data file will be stored, defaults to current directory.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates command objects from configuration data including address, memory ID, and binary file data.

Parameters:

config (Config) – Configuration object with command fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

classmethod parse(data)#

Parse command from bytes array.

Extracts command data from a byte array and creates a command instance with the parsed address, data, and memory ID. Validates that the command tag matches the expected type.

Parameters:

data (bytes) – Input data as bytes array to be parsed

Return type:

Self

Returns:

Command instance created from the parsed data

Raises:

SPSDKError – Invalid cmd_tag was found during parsing

class spsdk.sbfile.sb31.CmdLoadKeyBlob(offset, data, key_wrap_id, plain_input=False)#

Bases: BaseCmd

SB3.1 command for loading encrypted key blobs into device memory.

This command handles the secure loading of wrapped key material using NXP customer KEK (Key Encryption Key) for both internal and external secure keys. The command supports different key wrap versions and provides family-specific key ID resolution.

Variables:
  • CMD_TAG – Command identifier for load key blob operation.

  • FORMAT – Binary format string for command serialization.

Initialize SB3.1 command with key wrapping parameters.

Parameters:
  • offset (int) – Input offset for the command execution.

  • data (bytes) – Wrapped key blob data to be processed.

  • key_wrap_id (int) – Key wrap identifier (NXP_CUST_KEK_INT_SK = 16, NXP_CUST_KEK_EXT_SK = 17).

  • plain_input (bool) – Whether the input data is in plain format, defaults to False.

CMD_TAG = (10, 'loadKeyBlob')#
FORMAT = '<L2H2L'#
class KeyTypes(value)#

Bases: Enum

SB3.1 key type enumeration for customer KEK configurations.

This enumeration defines the available key types for NXP customer Key Encryption Key (KEK) configurations in SB3.1 secure boot files, supporting both internal and external key storage options.

NXP_CUST_KEK_EXT_SK = 2#
NXP_CUST_KEK_INT_SK = 1#
export()#

Export command as bytes array.

Serializes the command into a binary format according to the SB3.1 specification. The exported data includes command header with TAG, address, key wrap ID, length, and command-specific tag, followed by the actual data payload. The result is aligned to 16-byte boundary with zero padding.

Return type:

bytes

Returns:

Binary representation of the command ready for SB3.1 file inclusion.

property export_length: int#

Calculate the total export length including the command header and data.

This property returns the total size in bytes that the command will occupy when exported to binary format, including both the fixed-size command header and any variable-length data payload. The result is aligned to 16-byte boundary.

Returns:

Total length in bytes of the exported command.

get_config_context(data_path='./')#

Create configuration for the LOAD_KEY_BLOB command.

This method generates a configuration dictionary containing the command’s properties and settings, including offset, key wrap ID, and the key blob data. The key blob data is stored in a separate binary file for better management and security.

Parameters:

data_path (str) – Path where the key blob file will be stored.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod get_key_id(family, key_name)#

Get key ID based on family and key name.

The method retrieves the appropriate key identifier by looking up the chip family database and determining the correct key wraps version to use for the specified key type.

Parameters:
  • family (FamilyRevision) – Chip family revision to determine key mapping.

  • key_name (KeyTypes) – Key type, either NXP_CUST_KEK_INT_SK or NXP_CUST_KEK_EXT_SK.

Raises:

SPSDKValueError – Unsupported key wraps version found in database.

Return type:

int

Returns:

Integer value representing the key identifier.

property length: int#

Get data length.

Returns:

Length of the data in bytes.

classmethod load_from_config(config)#

Load configuration from dictionary to create command objects.

The method processes configuration data including offset, wrapping key ID, family revision, and input data format. It handles special cases for YAML boolean conversion and supports both hexadecimal and binary input formats.

Parameters:

config (Config) – Configuration object with command fields including offset, wrappingKeyId, family information, plainInput format, and input file path.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

Raises:

SPSDKValueError – When plainInput field is not a string type.

classmethod parse(data)#

Parse command from bytes array.

Deserializes a CmdLoadKeyBlob command from its binary representation by extracting the CMPA offset, key wrap ID, and key blob data.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command

Raises:

struct.error – If data format is invalid or insufficient data provided

Return type:

Self

Returns:

CmdLoadKeyBlob instance with parsed parameters

class spsdk.sbfile.sb31.CmdProgFuses(address, data)#

Bases: CmdLoadBase

Address will be address of fuse register.

Initialize SB3.1 command with address and data.

The constructor sets up the command with the provided address and data, and adjusts the length by dividing it by 4 to convert from bytes to words.

Parameters:
  • address (int) – Target address for the command operation.

  • data (bytes) – Binary data payload for the command.

CMD_TAG = (5, 'programFuses')#
HAS_MEMORY_ID_BLOCK = False#
get_config_context(data_path='./')#

Create configuration for the PROGRAM_FUSES command.

This method generates a configuration dictionary containing the command’s properties and settings, including the fuse register address and values to be programmed. Fuse values are represented as comma-separated hexadecimal or decimal values.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary to create command objects.

The method parses configuration data to extract address and fuse values, then creates command objects with the parsed data. Fuse values can be provided as a single integer or as a comma-separated string of values.

Parameters:

config (Config) – Configuration object containing address and values fields.

Return type:

list[Self]

Returns:

List of command objects created from the configuration data.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKValueError – Invalid data format or corrupted input data

Return type:

Self

Returns:

CmdProgFuses instance created from parsed data

class spsdk.sbfile.sb31.CmdProgIfr(address, data)#

Bases: CmdLoadBase

Address will be the address into the IFR region.

Constructor for SB3.1 command.

Initializes a new SB3.1 command with the specified address and data payload.

Parameters:
  • address (int) – Target address where the command will be executed

  • data (bytes) – Command data payload as bytes array

CMD_TAG = (6, 'programIFR')#
HAS_MEMORY_ID_BLOCK = False#
get_config_context(data_path='./')#

Create configuration for the PROGRAM_IFR command.

This method generates a configuration dictionary containing the command’s properties and settings, including the address into the IFR region and the data to be programmed. The IFR data is stored in a separate binary file for better management.

Parameters:

data_path (str) – Path where the IFR data file will be stored.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (Config) – Configuration object with command fields.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Invalid data format or parsing error

Return type:

Self

Returns:

CmdProgFuses instance created from parsed data

class spsdk.sbfile.sb31.CmdSectionHeader(length, section_uid=1, section_type=1)#

Bases: BaseClass

SB3.1 command section header representation.

This class represents a section header for SB3.1 secure boot file commands, providing functionality to create, parse, and export section header data with section UID, type, and length information.

Variables:
  • FORMAT – Binary format string for section header structure.

  • SIZE – Size of the section header in bytes.

Initialize Commands section with specified parameters.

Parameters:
  • length (int) – Length of the commands section in bytes.

  • section_uid (int) – Unique identifier for the section, defaults to 1.

  • section_type (int) – Type identifier for the section, defaults to 1.

FORMAT = '<4L'#
SIZE = 16#
export()#

Export command as bytes.

Serializes the command data into binary format using the predefined FORMAT structure.

Return type:

bytes

Returns:

Binary representation of the command containing section UID, type, length and padding.

classmethod parse(data)#

Parse command from bytes array.

The method deserializes a CmdSectionHeader object from binary data by unpacking the section UID, section type, and length fields according to the defined FORMAT.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command.

Raises:

SPSDKError – Raised when FORMAT is bigger than length of the data.

Return type:

Self

Returns:

CmdSectionHeader object parsed from the input data.

class spsdk.sbfile.sb31.EnumCmdTag(tag, label, description=None)#

Bases: SpsdkEnum

SB3.1 command tag enumeration.

This enumeration defines all supported command tags used in SB3.1 secure boot files. Each command tag represents a specific operation that can be executed during the secure boot process, such as memory operations, cryptographic functions, and system control commands.

CALL = (4, 'call')#
CHECK_LC = (15, 'checkLifecycle')#
CONFIGURE_MEMORY = (11, 'configureMemory')#
COPY = (8, 'copy')#
ERASE = (1, 'erase')#
EXECUTE = (3, 'execute')#
FILL_MEMORY = (12, 'fillMemory')#
FW_VERSION_CHECK = (13, 'checkFwVersion')#
LOAD = (2, 'load')#
LOAD_CMAC = (7, 'loadCMAC')#
LOAD_HASH_LOCKING = (9, 'loadHashLocking')#
LOAD_KEY_BLOB = (10, 'loadKeyBlob')#
NONE = (0, 'NONE')#
PROGRAM_FUSES = (5, 'programFuses')#
PROGRAM_IFR = (6, 'programIFR')#
RESET = (14, 'reset')#
WRITE_IFR = (16, 'writeIFR')#
spsdk.sbfile.sb31.parse_command(data)#

Parse command from bytes array.

Parses a command structure from the provided bytes data by extracting and validating the command tag, then creating the appropriate command object based on the tag type.

Parameters:

data (bytes) – Input data as bytes array containing the command structure.

Raises:
Return type:

object

Returns:

Parsed command object of the appropriate type.

SBFile Version 3.1. functions#

SPSDK SB3.1 key derivation and cryptographic helper functions.

This module provides key derivation functionality and utility functions for SB3.1 secure boot files, including block key derivation and data padding operations.

class spsdk.sbfile.sb31.functions.KeyDerivationMode(tag, label, description=None)#

Bases: SpsdkEnum

Key derivation mode enumeration for SB3.1 file format.

This enumeration defines the available modes for key derivation operations in SB3.1 secure boot files, including Key Derivation Key mode and Block Key Derivation mode.

BLK = (2, 'BLK', 'Block Key Derivation mode')#
KDK = (1, 'KDK', 'Key Derivation Key mode')#
class spsdk.sbfile.sb31.functions.KeyDerivator(pck, timestamp, key_length, kdk_access_rights)#

Bases: object

SPSDK Key Derivation Engine for SB3.1 format.

This class manages cryptographic key derivation operations for Secure Binary 3.1 files, providing functionality to generate Key Derivation Keys (KDK) from Part Common Keys (PCK) and derive block-specific encryption keys for secure boot image processing.

Initialize the KeyDerivator.

Sets up key derivation functionality with the provided parameters and derives the initial KeyDerivationKey.

Parameters:
  • pck (bytes) – Part Common Key, base user key for all key derivations.

  • timestamp (int) – Timestamp used for creating the KeyDerivationKey.

  • key_length (int) – Requested key length after derivation (128/256 bits).

  • kdk_access_rights (int) – KeyDerivationKey access rights.

get_block_key(block_number)#

Derive key for particular block.

Parameters:

block_number (int) – Block number for which to derive the key.

Return type:

bytes

Returns:

Derived key as bytes for the specified block.

spsdk.sbfile.sb31.functions.add_leading_zeros(byte_data, return_size)#

Add leading zeros to byte data to reach specified size.

Parameters:
  • byte_data (bytes) – Input data as bytes array.

  • return_size (int) – Target size of the output data in bytes.

Return type:

bytes

Returns:

Byte data padded with leading zeros to reach the specified size.

spsdk.sbfile.sb31.functions.add_trailing_zeros(byte_data, return_size)#

Pad byte data with trailing zeros to reach specified size.

Parameters:
  • byte_data (bytes) – Input data as bytes array to be padded.

  • return_size (int) – Target size of the output data in bytes.

Return type:

bytes

Returns:

Padded byte data with trailing zeros.

spsdk.sbfile.sb31.functions.derive_block_key(kdk, block_number, key_length, kdk_access_rights)#

Derive encryption AES key for given block.

This function uses the Key Derivation Key (KDK) to generate a block-specific AES encryption key using the specified parameters and block derivation mode.

Parameters:
  • kdk (bytes) – Key Derivation Key used as the base for key derivation.

  • block_number (int) – Block number used as derivation constant.

  • key_length (int) – Required key length in bits (128 or 256).

  • kdk_access_rights (int) – Key Derivation Key access rights value (0-3).

Return type:

bytes

Returns:

Derived AES key for the specified block.

spsdk.sbfile.sb31.functions.derive_kdk(pck, timestamp, key_length, kdk_access_rights)#

Derive the Key Derivation Key.

This function creates a KDK by deriving it from the Part Common Key using the provided timestamp and access rights parameters.

Parameters:
  • pck (bytes) – Part Common Key used as base for derivation.

  • timestamp (int) – Timestamp value used in KDK derivation process.

  • key_length (int) – Requested key length in bits (128 or 256).

  • kdk_access_rights (int) – KDK access rights level (valid range 0-3).

Return type:

bytes

Returns:

Derived Key Derivation Key as bytes.

SBFile Version 3.1. commands#

SPSDK SB3.1 secure boot file command implementations.

This module provides command classes and utilities for creating and managing SB3.1 (Secure Binary version 3.1) file commands. It includes implementations for various boot commands such as load, execute, erase, program fuses, and memory operations used in NXP MCU secure boot processes.

class spsdk.sbfile.sb31.commands.BaseCmd(address, length)#

Bases: BaseClass

Base command class for SB3.1 file format operations.

This abstract base class provides the foundation for all SB3.1 command types, defining common properties like address and length validation, export functionality, and the basic command structure format.

Variables:
  • FORMAT – Binary format string for command serialization.

  • SIZE – Size of the command header in bytes.

  • TAG – Command identification tag.

  • CMD_TAG – Enumerated command type identifier.

Initialize Commands header with address and length.

Parameters:
  • address (int) – Memory address for the command header.

  • length (int) – Length of the command data in bytes.

CMD_TAG = (0, 'NONE')#
FORMAT = '<4L'#
SIZE = 16#
TAG = 1437248085#
property address: int#

Get address value.

Returns:

The address value stored in this object.

export()#

Export command as bytes.

Serializes the command into binary format using the predefined FORMAT structure with TAG, address, length, and CMD_TAG values.

Return type:

bytes

Returns:

Binary representation of the command.

property export_length: int#

Get export length.

Returns:

The length of the exported command data.

get_config(data_path='./')#

Create configuration of the SecureBinary4 feature.

Generates a configuration object representing the current state of the SecureBinary4 instance.

Parameters:

data_path (str) – Path to store the data files of configuration.

Return type:

Config

Returns:

Configuration object with current SecureBinary4 settings.

get_config_context(data_path='./')#

Create configuration of the commands feature.

Abstract method that must be implemented by all inherited command classes. Each implementation should return a configuration object containing command-specific settings and parameters.

Parameters:

data_path (str) – Path to store the data files of configuration.

Raises:

NotImplementedError – Method must be implemented by derived classes.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod header_parse(data)#

Parse header command from bytes array.

Validates that the parsed command tag matches the expected command tag for this class.

Parameters:

data (bytes) – Input data as bytes array to parse the header from.

Raises:

SPSDKError – Raised if parsed command tag does not match the expected command tag.

Return type:

tuple[int, int]

Returns:

Tuple containing address and length extracted from the header.

classmethod header_parse_raw(data)#

Parse header command from bytes array.

The method extracts tag, address, length, and command values from the binary data and validates the tag against the expected class TAG value.

Parameters:

data (bytes) – Input data as bytes array containing the header command.

Raises:

SPSDKError – Raised if tag is not equal to required TAG.

Return type:

tuple[int, int, int]

Returns:

Tuple containing address, length, and command values.

property length: int#

Get length of the command.

Returns:

Length of the command in bytes.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates a list of command objects from the provided configuration dictionary. This is an abstract method that must be implemented by derived classes.

Parameters:

config (Config) – Dictionary with configuration fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

Raises:

NotImplementedError – Derived class has to implement this method.

classmethod parse(data)#

Parse command object from bytes array.

This is an abstract method that must be implemented by derived classes to handle specific command parsing logic.

Parameters:

data (bytes) – Input data as bytes array

Return type:

Self

Returns:

Parsed command object

Raises:

NotImplementedError – Derived class must implement this method

class spsdk.sbfile.sb31.commands.CmdCall(address)#

Bases: BaseCmd

Address will be the address to jump.

Initialize Command with specified address.

Parameters:

address (int) – Memory address where the command will be executed.

CMD_TAG = (4, 'call')#
cmd_tag = (4, 'call')#
get_config_context(data_path='./')#

Create configuration for the CALL command.

This method generates a configuration dictionary containing the command’s properties and settings, including the address to call. The CALL command executes code at a specified address but unlike EXECUTE, it returns control to the bootloader after completion.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Creates a list of command objects based on the provided configuration data.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKValueError – Invalid data format or corrupted command structure

Return type:

Self

Returns:

Parsed CmdCall command instance

class spsdk.sbfile.sb31.commands.CmdCheckLifecycle(lifecycle)#

Bases: BaseCmd

Command to check device lifecycle state.

Constructor for Command.

Parameters:

lifecycle (Lifecycle) – Lifecycle to be checked

CMD_TAG = (15, 'checkLifecycle')#
class Lifecycle(tag, label, description=None)#

Bases: SpsdkEnum

Device lifecycle states.

BRICKED = (255, 'BRICKED', 'Bricked')#
DEVELOP = (4227858435, 'DEVELOP', 'Develop')#
DEVELOP2 = (4160749575, 'DEVELOP2', 'Develop2')#
IN_FIELD = (4026531855, 'IN_FIELD', 'In Field')#
IN_FIELD_LOCKED = (805306575, 'IN_FIELD_LOCKED', 'In Field Locked')#
IN_FIELD_RETURN = (3758096415, 'IN_FIELD_RETURN', 'In Field Return')#
NXP_BLANK = (4278190080, 'NXP_BLANK', 'NXP Blank')#
NXP_DEV = (50331900, 'NXP_DEV', 'NXP Dev')#
NXP_FA = (2147483775, 'NXP_FA', 'NXP FA')#
NXP_FAB = (4261412865, 'NXP_FAB', 'NXP Fab')#
NXP_PROVISIONED = (4227858435, 'NXP_PROVISIONED', 'NXP Provisioned')#
export()#

Export command as bytes.

Return type:

bytes

get_config_context(data_path='./')#

Create configuration for the CHECK_LC command.

Parameters:

data_path (str) – Path to store any data files (not used for this command)

Return type:

Config

Returns:

Configuration object with command-specific settings

classmethod load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (Config) – Dictionary with configuration fields.

Return type:

list[Self]

Returns:

Command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Return type:

Self

Returns:

CmdCheckLifecycle

class spsdk.sbfile.sb31.commands.CmdConfigureMemory(address, memory_id=0)#

Bases: BaseCmd

SB3.1 command for configuring memory parameters.

This command sets up memory configuration parameters required before performing memory operations in the secure boot process. It specifies the target memory address and memory identifier for subsequent operations.

Variables:

CMD_TAG – Command tag identifier for CONFIGURE_MEMORY operations.

Initialize SB3.1 command with address and memory ID.

Parameters:
  • address (int) – Target address for the command operation.

  • memory_id (int) – Memory identifier, defaults to 0.

CMD_TAG = (11, 'configureMemory')#
export()#

Export command as bytes array.

Serializes the command into a binary format using the predefined FORMAT structure with TAG, memory_id, address, and CMD_TAG.tag fields.

Return type:

bytes

Returns:

Binary representation of the command.

get_config_context(data_path='./')#

Create configuration for the CONFIGURE_MEMORY command.

This method generates a configuration dictionary containing the command’s properties and settings, including the memory configuration address and memory ID. The CONFIGURE_MEMORY command sets up memory parameters required before performing operations on the specified memory.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Creates a list of command objects from the provided configuration data.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List containing a single command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Invalid data format or parsing failure

Return type:

Self

Returns:

CmdConfigureMemory instance created from parsed data

class spsdk.sbfile.sb31.commands.CmdCopy(address, length, destination_address=0, memory_id_from=0, memory_id_to=0)#

Bases: BaseCmd

Copy data from one place to another.

Initialize SB3.1 copy command.

Creates a new copy command that transfers data from one memory location to another, potentially between different memory regions.

Parameters:
  • address (int) – Source memory address to copy data from.

  • length (int) – Number of bytes to copy from source address.

  • destination_address (int) – Target memory address where data will be copied to.

  • memory_id_from (int) – Source memory region identifier.

  • memory_id_to (int) – Target memory region identifier.

CMD_TAG = (8, 'copy')#
export()#

Export command as bytes array.

Serializes the command into a binary format suitable for transmission or storage. The exported data includes the base command data followed by destination address, source memory ID, target memory ID, and a reserved field.

Return type:

bytes

Returns:

Binary representation of the command.

property export_length: int#

Export length of command in bytes.

Calculates the total export length including the base header (16 bytes) and additional COPY command specific fields (16 bytes).

Returns:

Length of command in bytes.

get_config_context(data_path='./')#

Create configuration for the COPY command.

This method generates a configuration dictionary containing the command’s properties and settings, including source address, destination address, size, and memory IDs. The COPY command transfers data between different memory regions, which is useful for copying firmware or data from one memory location to another.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates a command object by extracting configuration parameters from the provided Config object and returns it as a single-item list.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Deserializes a CmdCopy command from its binary representation by extracting the header information and command-specific parameters.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command

Return type:

Self

Returns:

CmdCopy instance created from the parsed data

Raises:

SPSDKError – Invalid padding detected in the command data

class spsdk.sbfile.sb31.commands.CmdErase(address, length, memory_id=0)#

Bases: BaseCmd

SB3.1 erase command for memory operations.

This command erases a specified address range in memory, with the erase operation automatically rounded up to the sector size. The command supports different memory types through memory ID specification.

Variables:

CMD_TAG – Command tag identifier for erase operations.

Initialize SB3.1 command with address, length and memory parameters.

Parameters:
  • address (int) – Target memory address for the command operation

  • length (int) – Number of bytes to be processed by the command

  • memory_id (int) – Identifier of the target memory interface, defaults to 0

CMD_TAG = (1, 'erase')#
export()#

Export command as bytes array.

Serializes the command into a binary format suitable for secure boot file generation. The exported data includes the base command data followed by memory ID and padding.

Return type:

bytes

Returns:

Binary representation of the command.

property export_length: int#

Get export length.

Calculate the total length of the exported command data, including the base command size and additional bytes for memory ID and padding.

Returns:

The length of the exported command data in bytes.

get_config_context(data_path='./')#

Create configuration for the ERASE command.

This method generates a configuration dictionary containing the command’s properties and settings, including memory address, length, and memory ID. The ERASE command erases a specified memory region, with the operation being rounded up to the sector size for the specified memory.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Creates command objects from configuration data including address, size, and memory ID.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

This method deserializes a CmdErase command from its binary representation, extracting the address, length, and memory ID while validating padding fields.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command

Return type:

Self

Returns:

CmdErase instance parsed from the input data

Raises:

SPSDKError – Invalid padding in the command data

class spsdk.sbfile.sb31.commands.CmdExecute(address)#

Bases: BaseCmd

Address will be the jump-to address.

Initialize Command with specified address.

Parameters:

address (int) – Memory address where the command will be executed.

CMD_TAG = (3, 'execute')#
get_config_context(data_path='./')#

Create configuration for the EXECUTE command.

This method generates a configuration dictionary containing the command’s properties and settings, including the address to jump to for execution. The EXECUTE command triggers execution at a specified address, which is typically used to start running code after it has been loaded into memory.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Creates a list of command objects based on the provided configuration data.

Parameters:

config (Config) – Configuration object containing command fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Invalid data format or parsing error

Return type:

Self

Returns:

CmdExecute instance created from parsed data

class spsdk.sbfile.sb31.commands.CmdFillMemory(address, length, pattern)#

Bases: BaseCmd

SB3.1 command for filling memory range with a specified pattern.

This command writes a repeating pattern to a contiguous block of memory, effectively initializing or clearing memory regions during secure boot operations.

Variables:

CMD_TAG – Command identifier for fill memory operations.

Initialize fill memory command.

Creates a command that fills a specified memory region with a given pattern.

Parameters:
  • address (int) – Target memory address to start filling

  • length (int) – Secure Binary bytes to fill in memory

  • pattern (int) – Fill pattern value to write to memory

CMD_TAG = (12, 'fillMemory')#
export()#

Export command as bytes array.

Serializes the command data including the pattern and padding into a binary format suitable for storage or transmission.

Return type:

bytes

Returns:

Binary representation of the command with pattern and padding.

property export_length: int#

Calculate the total export length including the command header and data.

Returns:

Total length in bytes of the exported command.

get_config_context(data_path='./')#

Create configuration for the FILL_MEMORY command.

This method generates a configuration dictionary containing the command’s properties and settings, including the starting address, size of the region to fill, and the pattern value to use for filling. The FILL_MEMORY command fills a specified memory region with a repeating pattern, which is useful for initializing memory areas or erasing sensitive data.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates a command object by extracting address, size, and pattern values from the provided configuration dictionary with default fallback values.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Deserializes a CmdErase command from its binary representation by extracting address, length, and pattern fields while validating padding bytes.

Parameters:

data (bytes) – Input data as bytes array

Return type:

Self

Returns:

CmdErase command instance

Raises:

SPSDKError – Invalid padding bytes detected

class spsdk.sbfile.sb31.commands.CmdFwVersionCheck(value, counter_id)#

Bases: BaseCmd

SB3.1 firmware version check command.

This command validates firmware version counters against stored values during secure boot processing. If the counter values do not match the expected values, the SB file execution is rejected, providing version rollback protection.

Variables:

CMD_TAG – Command identifier tag for firmware version check operations.

Initialize command with value and counter ID.

Parameters:
  • value (int) – Input value for the command

  • counter_id (CounterID) – Counter ID (NONSECURE = 1, SECURE = 2)

CMD_TAG = (13, 'checkFwVersion')#
class CounterID(tag, label, description=None)#

Bases: SpsdkEnum

Counter ID enumeration for firmware version check operations.

This enumeration defines the available counter identifiers used by the CmdFwVersionCheck command to specify which firmware version counter should be validated during secure boot operations.

BOOTLOADER = (5, 'bootloader')#
NONE = (0, 'none')#
NONSECURE = (1, 'nonsecure')#
RADIO = (3, 'radio')#
RADIO_LP = (7, 'radio_lp')#
SECURE = (2, 'secure')#
SNT = (4, 'snt')#
export()#

Export command as bytes array.

Serializes the command into a binary format using the predefined FORMAT structure with command tag, value, counter ID tag, and command tag.

Return type:

bytes

Returns:

Binary representation of the command.

get_config_context(data_path='./')#

Create configuration for the FW_VERSION_CHECK command.

This method generates a configuration dictionary containing the command’s properties and settings, including the version value to check and the counter ID. The FW_VERSION_CHECK command verifies that the firmware version meets or exceeds the specified value for the given counter type. This prevents downgrade attacks or installation of incompatible firmware. Counter IDs include: - none (0): No counter - nonsecure (1): Non-secure firmware counter - secure (2): Secure firmware counter - radio (3): Radio firmware counter - snt (4): SNT firmware counter - bootloader (5): Bootloader firmware counter

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary to create firmware version check commands.

This method parses the configuration dictionary to extract the value and counter ID parameters needed to create a firmware version check command instance.

Parameters:

config (Config) – Configuration dictionary containing ‘value’ and ‘counterId’ fields.

Raises:

SPSDKValueError – Invalid value format or unknown counter ID label.

Return type:

list[Self]

Returns:

List containing single firmware version check command object.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKValueError – Invalid data format or parsing error

Return type:

Self

Returns:

CmdFwVersionCheck instance created from parsed data

class spsdk.sbfile.sb31.commands.CmdLoad(address, data, memory_id=0, compress=False)#

Bases: CmdLoadBase

Data to write follows the range header.

Initialize Load command with specified parameters.

Parameters:
  • address (int) – Target memory address where data will be loaded

  • data (bytes) – Binary data to be loaded into memory

  • memory_id (int) – Target memory identifier (default: 0)

  • compress (bool) – Enable data compression for the load operation (default: False)

CMD_TAG = (2, 'load')#
get_config_context(data_path='./')#

Create configuration for the LOAD command.

This method generates a configuration dictionary containing the command’s properties and settings, including address, memory ID, and data representation. The LOAD command writes data to a specified memory address, which is essential for programming firmware, configuration parameters, or other data into device memory.

Parameters:

data_path (str) – Path to store any data files that might be created for large data.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary and create command objects.

Creates one or more command objects based on the configuration. When compression is enabled, the data is split into sector-aligned chunks and multiple commands are created.

Parameters:

config (Config) – Configuration object with command fields including address, memoryId, data source, compression settings, and sector size.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

Raises:

SPSDKValueError – Address not aligned to sector size when compression is enabled.

class spsdk.sbfile.sb31.commands.CmdLoadBase(address, data, memory_id=0, compress=False)#

Bases: BaseCmd

Base class for SB3.1 commands that load data into memory.

This class provides common functionality for commands that transfer data to target memory, including optional LZMA compression support and memory identification. It serves as the foundation for specific load command implementations in the SB3.1 format.

Variables:

HAS_MEMORY_ID_BLOCK – Indicates this command type includes memory ID information.

Initialize SB3.1 load command with data and optional compression.

The constructor sets up a load command that can optionally compress the data if compression results in significant size reduction (at least 16 bytes saved). When compression is enabled and beneficial, it calculates CRC and stores original data size for verification.

Parameters:
  • address (int) – Target memory address where data will be loaded

  • data (bytes) – Binary data to be loaded into memory

  • memory_id (int) – Target memory identifier (default: 0)

  • compress (bool) – Enable data compression if beneficial (default: False)

HAS_MEMORY_ID_BLOCK = True#
export()#

Export command as bytes array.

Serializes the command into a binary format suitable for storage or transmission. The method handles memory ID blocks, compression metadata, and ensures proper 16-byte alignment of the output data.

Return type:

bytes

Returns:

Binary representation of the command with proper alignment.

property export_length: int#

Get export length.

Calculate the total export length including the command header, memory ID block (if present), and the data payload (aligned to 16-byte boundary).

Returns:

The length of the exported command data in bytes.

classmethod load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (Config) – Dictionary with configuration fields.

Raises:

NotImplementedError – Method must be implemented by derived class.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

The method extracts command data from a byte array and validates the command tag before creating a new command instance.

Parameters:

data (bytes) – Input data as bytes array

Return type:

Self

Returns:

Command instance

Raises:

SPSDKError – Invalid cmd_tag was found

class spsdk.sbfile.sb31.commands.CmdLoadCmac(address, data, memory_id=0)#

Bases: CmdLoadBase

Load cmac. ROM is calculating cmac from loaded data.

Initialize Load command with target address and data.

Parameters:
  • address (int) – Target memory address where data will be loaded

  • data (bytes) – Binary data to be loaded into memory

  • memory_id (int) – Target memory identifier, defaults to 0

CMD_TAG = (7, 'loadCMAC')#
get_config_context(data_path='./')#

Create configuration for the LOAD_CMAC command.

This method generates a configuration dictionary containing the command’s properties and settings, including address, memory ID, and CMAC data. The CMAC data is stored in a separate binary file for better management.

Parameters:

data_path (str) – Path where the CMAC data file will be stored.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates command objects from configuration data including address, memory ID, and binary file data.

Parameters:

config (Config) – Configuration object with command fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

classmethod parse(data)#

Parse command from bytes array.

Extracts command data from a byte array and creates a command instance with the parsed address, data, and memory ID.

Parameters:

data (bytes) – Input data as bytes array

Return type:

Self

Returns:

Command instance

Raises:

SPSDKError – Invalid cmd_tag was found

class spsdk.sbfile.sb31.commands.CmdLoadHashLocking(address, data, memory_id=0)#

Bases: CmdLoadBase

SB3.1 Load Hash Locking command for secure boot operations.

This command loads hash data to a specified memory address while enabling ROM-based hash calculation and locking mechanisms. It extends the base load functionality with additional security features including hash verification and memory protection.

Variables:

CMD_TAG – Command identifier for load hash locking operations.

Initialize Load command with target address and data.

Parameters:
  • address (int) – Target memory address where data will be loaded

  • data (bytes) – Binary data to be loaded into memory

  • memory_id (int) – Target memory identifier, defaults to 0

CMD_TAG = (9, 'loadHashLocking')#
export()#

Export command as bytes array.

Exports the command data by calling the parent class export method and appending 64 null bytes for padding or alignment purposes.

Return type:

bytes

Returns:

Command data as bytes with additional padding.

property export_length: int#

Export length of command.

Returns:

Length of command in bytes.

get_config_context(data_path='./')#

Create configuration for the LOAD_HASH_LOCKING command.

This method generates a configuration dictionary containing the command’s properties and settings, including address, memory ID, and hash data. The hash data is stored in a separate binary file for better management.

Parameters:

data_path (str) – Path where the hash data file will be stored, defaults to current directory.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

The method creates command objects from configuration data including address, memory ID, and binary file data.

Parameters:

config (Config) – Configuration object with command fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

classmethod parse(data)#

Parse command from bytes array.

Extracts command data from a byte array and creates a command instance with the parsed address, data, and memory ID. Validates that the command tag matches the expected type.

Parameters:

data (bytes) – Input data as bytes array to be parsed

Return type:

Self

Returns:

Command instance created from the parsed data

Raises:

SPSDKError – Invalid cmd_tag was found during parsing

class spsdk.sbfile.sb31.commands.CmdLoadKeyBlob(offset, data, key_wrap_id, plain_input=False)#

Bases: BaseCmd

SB3.1 command for loading encrypted key blobs into device memory.

This command handles the secure loading of wrapped key material using NXP customer KEK (Key Encryption Key) for both internal and external secure keys. The command supports different key wrap versions and provides family-specific key ID resolution.

Variables:
  • CMD_TAG – Command identifier for load key blob operation.

  • FORMAT – Binary format string for command serialization.

Initialize SB3.1 command with key wrapping parameters.

Parameters:
  • offset (int) – Input offset for the command execution.

  • data (bytes) – Wrapped key blob data to be processed.

  • key_wrap_id (int) – Key wrap identifier (NXP_CUST_KEK_INT_SK = 16, NXP_CUST_KEK_EXT_SK = 17).

  • plain_input (bool) – Whether the input data is in plain format, defaults to False.

CMD_TAG = (10, 'loadKeyBlob')#
FORMAT = '<L2H2L'#
class KeyTypes(value)#

Bases: Enum

SB3.1 key type enumeration for customer KEK configurations.

This enumeration defines the available key types for NXP customer Key Encryption Key (KEK) configurations in SB3.1 secure boot files, supporting both internal and external key storage options.

NXP_CUST_KEK_EXT_SK = 2#
NXP_CUST_KEK_INT_SK = 1#
export()#

Export command as bytes array.

Serializes the command into a binary format according to the SB3.1 specification. The exported data includes command header with TAG, address, key wrap ID, length, and command-specific tag, followed by the actual data payload. The result is aligned to 16-byte boundary with zero padding.

Return type:

bytes

Returns:

Binary representation of the command ready for SB3.1 file inclusion.

property export_length: int#

Calculate the total export length including the command header and data.

This property returns the total size in bytes that the command will occupy when exported to binary format, including both the fixed-size command header and any variable-length data payload. The result is aligned to 16-byte boundary.

Returns:

Total length in bytes of the exported command.

get_config_context(data_path='./')#

Create configuration for the LOAD_KEY_BLOB command.

This method generates a configuration dictionary containing the command’s properties and settings, including offset, key wrap ID, and the key blob data. The key blob data is stored in a separate binary file for better management and security.

Parameters:

data_path (str) – Path where the key blob file will be stored.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod get_key_id(family, key_name)#

Get key ID based on family and key name.

The method retrieves the appropriate key identifier by looking up the chip family database and determining the correct key wraps version to use for the specified key type.

Parameters:
  • family (FamilyRevision) – Chip family revision to determine key mapping.

  • key_name (KeyTypes) – Key type, either NXP_CUST_KEK_INT_SK or NXP_CUST_KEK_EXT_SK.

Raises:

SPSDKValueError – Unsupported key wraps version found in database.

Return type:

int

Returns:

Integer value representing the key identifier.

property length: int#

Get data length.

Returns:

Length of the data in bytes.

classmethod load_from_config(config)#

Load configuration from dictionary to create command objects.

The method processes configuration data including offset, wrapping key ID, family revision, and input data format. It handles special cases for YAML boolean conversion and supports both hexadecimal and binary input formats.

Parameters:

config (Config) – Configuration object with command fields including offset, wrappingKeyId, family information, plainInput format, and input file path.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

Raises:

SPSDKValueError – When plainInput field is not a string type.

classmethod parse(data)#

Parse command from bytes array.

Deserializes a CmdLoadKeyBlob command from its binary representation by extracting the CMPA offset, key wrap ID, and key blob data.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command

Raises:

struct.error – If data format is invalid or insufficient data provided

Return type:

Self

Returns:

CmdLoadKeyBlob instance with parsed parameters

class spsdk.sbfile.sb31.commands.CmdProgFuses(address, data)#

Bases: CmdLoadBase

Address will be address of fuse register.

Initialize SB3.1 command with address and data.

The constructor sets up the command with the provided address and data, and adjusts the length by dividing it by 4 to convert from bytes to words.

Parameters:
  • address (int) – Target address for the command operation.

  • data (bytes) – Binary data payload for the command.

CMD_TAG = (5, 'programFuses')#
HAS_MEMORY_ID_BLOCK = False#
get_config_context(data_path='./')#

Create configuration for the PROGRAM_FUSES command.

This method generates a configuration dictionary containing the command’s properties and settings, including the fuse register address and values to be programmed. Fuse values are represented as comma-separated hexadecimal or decimal values.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary to create command objects.

The method parses configuration data to extract address and fuse values, then creates command objects with the parsed data. Fuse values can be provided as a single integer or as a comma-separated string of values.

Parameters:

config (Config) – Configuration object containing address and values fields.

Return type:

list[Self]

Returns:

List of command objects created from the configuration data.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKValueError – Invalid data format or corrupted input data

Return type:

Self

Returns:

CmdProgFuses instance created from parsed data

class spsdk.sbfile.sb31.commands.CmdProgIfr(address, data)#

Bases: CmdLoadBase

Address will be the address into the IFR region.

Constructor for SB3.1 command.

Initializes a new SB3.1 command with the specified address and data payload.

Parameters:
  • address (int) – Target address where the command will be executed

  • data (bytes) – Command data payload as bytes array

CMD_TAG = (6, 'programIFR')#
HAS_MEMORY_ID_BLOCK = False#
get_config_context(data_path='./')#

Create configuration for the PROGRAM_IFR command.

This method generates a configuration dictionary containing the command’s properties and settings, including the address into the IFR region and the data to be programmed. The IFR data is stored in a separate binary file for better management.

Parameters:

data_path (str) – Path where the IFR data file will be stored.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (Config) – Configuration object with command fields.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Invalid data format or parsing error

Return type:

Self

Returns:

CmdProgFuses instance created from parsed data

class spsdk.sbfile.sb31.commands.CmdReset#

Bases: BaseCmd

SB3.1 Reset command implementation.

This class represents a reset command that triggers a system reset of the target device. The reset operation is typically used to complete a programming sequence or ensure the device starts from a clean state after applying configuration changes. This command requires no parameters and performs a straightforward system reset operation.

Variables:

CMD_TAG – Command identifier tag for the reset operation.

Initialize reset command.

Creates a new reset command instance with zero address and length values. This command is used to reset the target device during secure boot execution.

CMD_TAG = (14, 'reset')#
get_config_context(data_path='./')#

Create configuration for the RESET command.

This method generates a minimal configuration dictionary as the RESET command doesn’t require any specific parameters. The RESET command triggers a system reset of the device, which is useful for completing a programming sequence or to ensure the device starts from a clean state after applying configuration changes.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings (empty for this command).

classmethod load_from_config(config)#

Load configuration from dictionary.

Parameters:

config (Config) – Dictionary with configuration fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Invalid data format or parsing error

Return type:

Self

Returns:

CmdReset instance

class spsdk.sbfile.sb31.commands.CmdSectionHeader(length, section_uid=1, section_type=1)#

Bases: BaseClass

SB3.1 command section header representation.

This class represents a section header for SB3.1 secure boot file commands, providing functionality to create, parse, and export section header data with section UID, type, and length information.

Variables:
  • FORMAT – Binary format string for section header structure.

  • SIZE – Size of the section header in bytes.

Initialize Commands section with specified parameters.

Parameters:
  • length (int) – Length of the commands section in bytes.

  • section_uid (int) – Unique identifier for the section, defaults to 1.

  • section_type (int) – Type identifier for the section, defaults to 1.

FORMAT = '<4L'#
SIZE = 16#
export()#

Export command as bytes.

Serializes the command data into binary format using the predefined FORMAT structure.

Return type:

bytes

Returns:

Binary representation of the command containing section UID, type, length and padding.

classmethod parse(data)#

Parse command from bytes array.

The method deserializes a CmdSectionHeader object from binary data by unpacking the section UID, section type, and length fields according to the defined FORMAT.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command.

Raises:

SPSDKError – Raised when FORMAT is bigger than length of the data.

Return type:

Self

Returns:

CmdSectionHeader object parsed from the input data.

class spsdk.sbfile.sb31.commands.CmdWriteIfr(address, data, ifr_type)#

Bases: BaseCmd

SB3.1 command for writing data to IFR (Internal Flash Region) memory.

This command handles writing configuration data to specific IFR regions including CFPA (Customer Field Programmable Area) and CMPA (Certified Manufacturer Programmable Area) sections of the target device.

Variables:

CMD_TAG – Command identifier for IFR write operations.

Initialize WriteIfr command with address, data, and IFR type.

Parameters:
  • address (int) – Target address for the IFR write operation.

  • data (bytes) – Binary data to be written to the IFR.

  • ifr_type (WriteIfrType) – Type of IFR write operation to perform.

CMD_TAG = (16, 'writeIFR')#
class WriteIfrType(value)#

Bases: Enum

Write IFR (Internal Flash Region) operation types for SB3.1 commands.

This enumeration defines the available types of IFR write operations that can be performed in Secure Binary 3.1 files, specifying which configuration areas should be written during the provisioning process.

CFPA = 0#
CFPA_AND_CMPA = 1#
export()#

Export command as bytes array.

Serializes the command into a binary format by combining the parent class export data with IFR type information and command data, aligned to 16 bytes.

Return type:

bytes

Returns:

Binary representation of the command.

get_config_context(data_path='./')#

Create configuration for the WRITE_IFR command.

This method generates a configuration dictionary containing the command’s properties and settings, including the address into the IFR region and the data to be written. The IFR data is stored in a separate binary file for better management.

Parameters:

data_path (str) – Path where the IFR data file will be stored.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)#

Load configuration from dictionary to create WriteIfr command instances.

Creates WriteIfr command objects from configuration data, automatically setting the address to 0 as it points to the beginning of IFR region.

Parameters:

config (Config) – Configuration dictionary containing command fields and IFR type.

Return type:

list[Self]

Returns:

List containing single WriteIfr command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parses a CmdWriteIfr command from the provided byte data by extracting the address, length, IFR type, and IFR data components.

Parameters:

data (bytes) – Input data as bytes array containing the command structure.

Return type:

Self

Returns:

CmdWriteIfr instance created from the parsed data.

Raises:

SPSDKError – Invalid padding in the command structure.

spsdk.sbfile.sb31.commands.load_cmd_data_from_cfg(config)#

Load command data from configuration.

This function attempts to extract binary data from configuration using multiple approaches: 1. Direct conversion to bytes if possible 2. Parsing as list of values or comma-separated string 3. Loading from a file specified in configuration The method provides backward compatibility for obsolete configuration keys (value/values/file).

Parameters:

config (Config) – Configuration object containing data source specification.

Return type:

bytes

Returns:

Binary data extracted from configuration.

Raises:

SPSDKError – When data cannot be loaded from any source.

spsdk.sbfile.sb31.commands.parse_command(data)#

Parse command from bytes array.

Parses a command structure from the provided bytes data by extracting and validating the command tag, then creating the appropriate command object based on the tag type.

Parameters:

data (bytes) – Input data as bytes array containing the command structure.

Raises:
Return type:

object

Returns:

Parsed command object of the appropriate type.

SBFile Version 3.1. images#

SPSDK SecureBinary V3.1 image generation and management.

This module provides functionality for creating, parsing, and managing SecureBinary V3.1 format images used in NXP MCU secure boot process.

class spsdk.sbfile.sb31.images.SecureBinary31(family, cert_block, firmware_version, sb_commands, description=None, is_nxp_container=False, flags=0, signature_provider=None, signature=None)#

Bases: FeatureBaseClass

Secure Binary v3.1 container for NXP MCU secure provisioning.

This class represents a complete SB3.1 secure binary file that contains encrypted commands and data for secure device provisioning. It manages the creation, validation, and export of SB3.1 containers with proper certification blocks, signatures, and command sequences.

Variables:

FEATURE – Database feature identifier for SB3.1 support.

Constructor for Secure Binary v3.1 data container.

Initializes a new Secure Binary v3.1 container with the provided configuration, commands, and signing information. The container requires either a signature provider or a pre-computed signature for authentication.

Parameters:
  • family (FamilyRevision) – Device family revision information.

  • cert_block (CertBlockV21) – Certificate block for authentication.

  • firmware_version (int) – Firmware version (must be greater than current CMPA record).

  • sb_commands (SecureBinary31Commands) – SecureBinary31Commands object containing the commands to execute.

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None.

  • is_nxp_container (bool) – Whether this is an NXP provisioning SB file, defaults to False.

  • flags (int) – Additional flags for the SB file, defaults to 0.

  • signature_provider (Optional[SignatureProvider]) – Signature provider for signing the SB3.1 image, defaults to None.

  • signature (Optional[bytes]) – Pre-computed signature bytes if signature_provider not used, defaults to None.

Raises:

SPSDKError – If neither signature_provider nor signature is provided.

FEATURE: str = 'sb31'#
export()#

Generate binary output of SB3.1 file.

The method validates the file structure, exports commands to get their hash, updates the header with block count and total length, sets the next block hash, and assembles the final binary data including header, certificate block, signature, and command blocks.

Raises:

AssertionError – When signature is not provided and signature provider is not used.

Return type:

bytes

Returns:

Content of SB3.1 file in bytes.

classmethod get_commands_validation_schemas(family)#

Create the list of validation schemas for SB3.1 commands.

The method retrieves the base SB3.1 schema and customizes it based on the target family’s capabilities. It filters out unsupported commands and adjusts compression-related properties if the family doesn’t support compression features.

Parameters:

family (FamilyRevision) – Family description containing device-specific configuration.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas customized for the specified family.

get_config(data_path='./')#

Create configuration of the SB3.1 image.

The method generates a complete configuration dictionary containing all SB3.1 image properties including header information, certificate block, and commands configuration.

Parameters:

data_path (str) – Path to store the data files of configuration.

Return type:

Config

Returns:

Configuration object with SB3.1 image settings.

static get_current_timestamp()#

Get current timestamp as seconds since January 1, 2000.

Return type:

int

Returns:

Integer representing seconds elapsed since January 1, 2000.

classmethod get_devhsm_commands_validation_schemas(family)#

Create the list of validation schemas for DevHSM commands.

The method retrieves the base SB3 schema and filters commands based on what’s supported by the specific device family. It also makes the ‘commands’ field optional for device HSM configurations.

Parameters:

family (FamilyRevision) – Family description containing device-specific information.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas with filtered commands for the family.

get_rkth()#

Get the Root Key Table Hash (RKTH) from the certificate block.

Return type:

bytes

Returns:

RKTH as bytes if available, empty bytes otherwise.

classmethod get_validation_schemas(family)#

Create the list of validation schemas for SB3.1 image configuration.

The method retrieves and combines validation schemas from multiple sources including MBI, SB3.1, and general configuration schemas, along with command-specific schemas for the specified family.

Parameters:

family (FamilyRevision) – Family description containing chip family and revision information.

Return type:

list[dict[str, Any]]

Returns:

List of validation schema dictionaries for configuration validation.

classmethod load_from_config(config)#

Creates an instance of SecureBinary31 from configuration.

The method parses the configuration to extract all necessary parameters including family revision, certificate block, commands, and signature provider to create a complete Secure Binary V3.1 instance.

Parameters:

config (Config) – Input standard configuration containing SB3.1 parameters.

Return type:

Self

Returns:

Instance of Secure Binary V3.1 class.

classmethod parse(data, family=None, pck=None, kdk_access_rights=0)#

Parse SecureBinary31 object from binary data.

This method reconstructs a complete SecureBinary31 object by parsing the binary representation, including header, certificate block, signature, and commands sections.

Parameters:
  • data (bytes) – Binary data containing the complete SB3.1 file to parse

  • family (Optional[FamilyRevision]) – Family revision information required for proper parsing

  • pck (Optional[str]) – Part Common Key needed for decrypting encrypted sections

  • kdk_access_rights (int) – Key Derivation Key access rights for key derivation

Return type:

Self

Returns:

Constructed SecureBinary31 object with all parsed components

Raises:

SPSDKError – When parsing fails or data is invalid

validate()#

Validate the settings of class members.

This method performs comprehensive validation of SB3.1 configuration including signature provider verification, raw signature length validation, and validation of header and commands components.

Raises:

SPSDKError – Invalid configuration of SB3.1 class members, invalid signature provider, missing certificate block for public key verification, invalid signature length, or missing signature configuration.

Return type:

None

static validate_header(binary)#

Validate SB3.1 header in binary data.

This method parses the SB3.1 header from the provided binary data and validates its structure and content to ensure it conforms to the SB3.1 specification.

Parameters:

binary (bytes) – Binary data containing the SB3.1 header to be validated.

Raises:

SPSDKError – Invalid header of SB3.1 data.

Return type:

None

class spsdk.sbfile.sb31.images.SecureBinary31Commands(family, hash_type, timestamp=None, encryption_provider=<spsdk.sbfile.utils.encryption_provider.NoEncryption object>)#

Bases: BaseClass

SB3.1 Commands Container.

This class manages a collection of SB3.1 (Secure Binary 3.1) commands that form the executable payload of a secure binary file. It handles command organization, encryption, hashing, and serialization for NXP MCU secure boot operations.

Variables:
  • FEATURE – Database feature identifier for SB3.1.

  • SB_COMMANDS_NAME – Human-readable name for SB3.1 commands.

  • SUPPORTED_HASHES – List of supported hash algorithms.

  • PCK_SIZES – Supported Part Common Key sizes in bits.

Initialize container for SB3.1 commands.

Parameters:
  • family (FamilyRevision) – Device family and revision information.

  • hash_type (EnumHashAlgorithm) – Hash algorithm type used in commands binary block.

  • timestamp (Optional[int]) – Timestamp used for encryption, defaults to current timestamp if None.

  • encryption_provider (EncryptionProvider) – Encryption provider instance, defaults to NoEncryption.

Raises:

SPSDKValueError – Invalid hash type not supported by the family.

FEATURE = 'sb31'#
PCK_SIZES = [256, 128]#
SB_COMMANDS_NAME = 'SB3.1'#
SUPPORTED_HASHES = [EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'), EnumHashAlgorithm(tag=2, label='sha384', description='SHA384')]#
add_command(command)#

Add Secure Binary command to the image.

The method accepts either a single command or a list of commands and adds them to the internal commands collection.

Parameters:

command (Union[BaseCmd, list[BaseCmd]]) – Single command or list of commands to be added to the image.

Return type:

None

export()#

Export commands as bytes.

The method retrieves command blocks to export and processes them into a byte representation suitable for serialization or transmission.

Return type:

bytes

Returns:

Serialized command data as bytes.

get_cmd_blocks_to_export()#

Export command blocks as byte chunks for SB3.1 file generation.

This method processes all commands in the section, creates a section header, and splits the combined data into appropriately sized blocks. The last block is aligned if fixed block length is required.

Return type:

list[bytes]

Returns:

List of byte blocks containing the exported command section data.

get_config(data_path='./')#

Create configuration of the SecureBinary4 feature.

Generates a configuration object representing the current state of the SecureBinary4 instance. If encryption is enabled, writes the key derivation key to a file in the specified data path.

Parameters:

data_path (str) – Path to store the data files of configuration.

Return type:

Config

Returns:

Configuration object with current SecureBinary4 settings.

insert_command(index, command)#

Insert Secure Binary command at specified index.

Parameters:
  • index (int) – Position where to insert the command. Use -1 to append at the end.

  • command (BaseCmd) – The Secure Binary command to insert.

Return type:

None

property is_encrypted: bool#

Check if commands are encrypted.

Returns:

True if commands are encrypted, False otherwise.

classmethod load_from_config(config, hash_type=EnumHashAlgorithm(tag=1, label='sha256', description='SHA256'), timestamp=None, load_just_commands=False)#

Load SecureBinary commands from configuration.

Creates a SecureBinary31Commands instance from configuration data, including encryption setup and command loading. Handles timestamp resolution and encryption provider configuration based on the provided settings.

Parameters:
  • config (Config) – Configuration object containing SecureBinary settings and commands.

  • hash_type (EnumHashAlgorithm) – Hash algorithm for command block hashing, defaults to SHA256.

  • timestamp (Optional[int]) – Timestamp for commands, defaults to None (uses current time).

  • load_just_commands (bool) – If True, loads only commands without encryption setup, defaults to False.

Return type:

Self

Returns:

Configured SecureBinary31Commands instance with loaded commands.

classmethod load_pck(pck_src, search_paths=None)#

Load Part Common Key from source.

The method tries to load PCK with different supported sizes and returns the first successfully parsed key bytes.

Parameters:
  • pck_src (str) – Path to file or hex string containing the Part Common Key.

  • search_paths (Optional[list[str]]) – List of additional directories to search for PCK file.

Return type:

bytes

Returns:

Parsed PCK as bytes.

Raises:

SPSDKError – If PCK cannot be loaded with any supported size.

classmethod parse(data, family=None, block_size=256, pck=None, block1_hash=None, hash_type=None, kdk_access_rights=0, timestamp=None)#

Parse binary data into SecureBinary31Commands.

This method reconstructs SecureBinary31Commands from binary SB31 format by parsing blocks, decrypting if needed, and extracting individual commands. Blocks are processed in reverse order and commands are parsed according to their specific types.

Parameters:
  • data (bytes) – Binary data containing SB31 commands.

  • family (Optional[FamilyRevision]) – FamilyRevision instance with device family information.

  • block_size (int) – Size of each command block in bytes, defaults to 256.

  • pck (Optional[str]) – Part Common Key string required for decryption of encrypted data.

  • block1_hash (Optional[bytes]) – Hash bytes of the first block for validation.

  • hash_type (Optional[EnumHashAlgorithm]) – EnumHashAlgorithm specifying hash algorithm used in binary data.

  • kdk_access_rights (int) – Key Derivation Key access rights, defaults to 0.

  • timestamp (Optional[int]) – Timestamp integer used for decryption (required for encrypted commands).

Return type:

Self

Returns:

Initialized SecureBinary31Commands object with parsed commands.

Raises:
  • SPSDKError – When parsing fails, data is invalid, or required parameters missing.

  • SPSDKValueError – When an invalid hash type is provided.

classmethod parse_block_header(block_data, offset, block_size, block_hash, hash_type)#

Parse the block header from the input data and verify its integrity.

The method extracts block information including block number, next block hash, and encrypted data from the binary block data. It also performs hash verification to ensure block integrity.

Parameters:
  • block_data (bytes) – Binary data of the block

  • offset (int) – Offset in the data where the header begins

  • block_size (int) – Size of the block in bytes

  • block_hash (bytes) – Expected hash of the block for verification

  • hash_type (EnumHashAlgorithm) – Hash algorithm used for block hashing

Return type:

tuple[int, int, bytes, bytes]

Returns:

Tuple containing block number, block size, next block hash, and encrypted block data

Raises:

SPSDKError – When the block hash verification fails

process_cmd_blocks_to_export(data_blocks)#

Process given data blocks for export to SB3.1 format.

This method takes a list of data blocks and processes them for export by encrypting each block, adding block numbers and hash chains, and combining them into the final exportable format. The blocks are processed in reverse order to build the hash chain correctly.

Parameters:

data_blocks (list[bytes]) – List of byte arrays representing the data blocks to be processed.

Return type:

bytes

Returns:

Final processed data ready for export as bytes.

set_commands(commands)#

Set all Secure Binary commands at once.

Parameters:

commands (list[BaseCmd]) – List of BaseCmd objects to be set as the commands for this instance.

Return type:

None

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of SB3.1 commands blob class members.

Return type:

None

validate_command_rules()#

Validate commands against device-specific rules.

This method retrieves command validation rules from the device database and applies them to verify that all commands in the image comply with the device-specific requirements and constraints.

Raises:

SPSDKError – When command validation rules are violated.

Return type:

None

class spsdk.sbfile.sb31.images.SecureBinary31Header(firmware_version, hash_type, cert_block=None, description=None, timestamp=None, is_nxp_container=False, flags=0)#

Bases: BaseClass

SecureBinary V3.1 header representation for NXP MCU secure boot files.

This class manages the header structure (Block 0) of SecureBinary format version 3.1, including metadata such as firmware version, hash algorithms, certificate blocks, and container properties for secure provisioning operations.

Variables:
  • MAGIC – Magic bytes identifier for SB v3.1 format.

  • FORMAT_VERSION – Version string for this SecureBinary format.

  • HEADER_SIZE – Size of the header structure in bytes.

  • DESCRIPTION_LENGTH – Maximum length for description field.

Initialize the SecureBinary V3.1 Header.

Parameters:
  • firmware_version (int) – Firmware version (must be bigger than current CMPA record)

  • hash_type (EnumHashAlgorithm) – Hash type used in commands binary block

  • cert_block (Optional[CertBlockV21]) – Certificate block v2.1 for the Block 0, defaults to None

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None

  • timestamp (Optional[int]) – Timestamp (number of seconds since Jan 1st, 2000), if None use current time

  • is_nxp_container (bool) – NXP provisioning SB file, defaults to False

  • flags (int) – Flags for SB file, defaults to 0

Raises:

SPSDKValueError – Invalid hash type provided

DESCRIPTION_LENGTH = 16#
FORMAT_VERSION = '3.1'#
HEADER_FORMAT = '<4s2H3LQ4L16s'#
HEADER_SIZE = 60#
MAGIC = b'sbv3'#
property block_size: int#

Calculate the data block size.

The method computes the total size of a data block by adding the fixed overhead (4 bytes) plus signature size (256 bytes) plus the hash length based on the configured hash type.

Returns:

Total data block size in bytes.

property cert_block_offset: int#

Calculate the offset to the Certification block.

The offset is computed based on the fixed structure layout: 1 field of 8 bytes, 9 fields of 4 bytes each, 16 bytes of additional data, plus the hash length determined by the hash type.

Returns:

Offset in bytes to the Certification block.

export()#

Export the SB 3.1 file to binary format.

Converts the SB 3.1 header structure into its packed binary representation using the predefined header format. The method processes the format version string and packs all header fields according to the SB 3.1 specification.

Return type:

bytes

Returns:

Packed binary representation of the SB 3.1 header.

export_full_block0()#

Export the complete Block 0 data including header, hash, and certificate block.

This data is used for signature calculation and contains all necessary components of Block 0 except the signature itself.

Return type:

bytes

Returns:

Binary data of Block 0 without signature.

Raises:

SPSDKError – If cert_block is required but not set.

classmethod parse(data)#

Parse binary data into SecureBinary31Header.

Parses the provided binary data and creates a SecureBinary31Header instance with validated header fields including magic number, version, block configuration, and hash type determination.

Parameters:

data (bytes) – Binary data containing the SB31 header to parse.

Raises:

SPSDKError – Invalid input size, magic mismatch, unsupported version, invalid block size, or header validation failure.

Return type:

Self

Returns:

Parsed SecureBinary31Header instance.

set_next_block_hash(hash_value)#

Set the hash of the next block.

Parameters:

hash_value (bytes) – Hash value of the next block

Raises:

SPSDKError – If hash length doesn’t match the configured hash type

Return type:

None

update(commands)#

Update the volatile fields in header by real commands and certification block data.

The method calculates and sets the block count and total image length based on the provided commands and existing certification block. It accounts for header size, hash size, optional certification block size, and signature size.

Parameters:

commands (SecureBinary31Commands) – SB3.1 Commands block containing the command data.

Return type:

None

validate()#

Validate the settings of SB3.1 header blob class members.

Performs comprehensive validation of all required class members including flags, block count, hash type, block size, image type, firmware version, timestamp, image total length, certification block offset, description, and next block hash. Optionally validates the certificate block if present.

Raises:

SPSDKError – Invalid configuration of SB3.1 header blob class members.

Return type:

None

SBFile Version X#

SPSDK SecureBinary X image generation and management utilities.

This module provides functionality for creating and handling SecureBinary X (SBX) images, including TPM HSM blob management, secure binary headers, commands, and complete SBX image construction for NXP MCU secure provisioning.

class spsdk.sbfile.sbx.images.SecureBinaryX(family, firmware_version, tphsm_blob, commands, description=None, image_type=SecureBinaryXType.OEM_PROVISIONING, signature_provider=None, flags=0)#

Bases: FeatureBaseClass

Secure Binary X (SBX) container for NXP MCU secure provisioning.

This class manages the creation, validation, and export of Secure Binary X format files used for secure provisioning and firmware updates on NXP MCUs. It handles SBX headers, command sequences, cryptographic signatures, and TP-HSM integration.

Variables:

FEATURE – Database manager feature identifier for SBX support.

Constructor for Secure Binary vX data container.

Parameters:
  • family (FamilyRevision) – The MCU/MPU family.

  • firmware_version (int) – Firmware version.

  • tphsm_blob (Optional[TpHsmBlob]) – TP HSM blob, optional.

  • commands (SecureBinaryXCommands) – SecureBinaryX commands container.

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None.

  • image_type (SecureBinaryXType) – SecureBinaryXType, defaults to OEM_PROVISIONING.

  • signature_provider (Optional[SignatureProvider]) – Signature provider to final sign of SBX image in case of OEM and NXP_PROVISIONING types, defaults to None.

  • flags (int) – Flags for SB file, defaults to 0.

Raises:

SPSDKError – If signature provider is not provided for OEM and NXP_PROVISIONING images.

FEATURE: str = 'sbx'#
export()#

Generate binary output of SBx file.

The method exports the complete SBx file structure including header, TPHSM blob, hash of previous block, signature placeholder, and commands data.

Raises:

SPSDKError – TPHSM blob must be loaded first

Return type:

bytes

Returns:

Content of SBx file in bytes.

export_header(final_hash=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')#

Export SBx header without signature for encryption on device.

The method exports the SB header combined with TPHSM blob and final hash for device-side encryption processing.

Parameters:

final_hash (bytes) – Hash of the next block to be included in header.

Raises:

SPSDKError – TPHSM blob must be loaded first.

Return type:

bytes

Returns:

Plain header without signature in bytes.

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, include_test_configuration=False)#

Create the list of validation schemas for SBX image configuration.

The method retrieves and combines validation schemas from MBI and SBX schema files, including family-specific schemas and optional test configuration schemas.

Parameters:
  • family (FamilyRevision) – Family description specifying the target MCU family.

  • include_test_configuration (bool) – Add also testing configuration schemas.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas for SBX image configuration.

property isk_signed: bool#

Check if SBx image is signed by ISK certificate.

This method determines whether the secure binary image uses ISK (Intermediate Signing Key) certificate for signing by checking if the image type is OEM or NXP_PROVISIONING.

Returns:

True if the image is signed by ISK certificate, False otherwise.

classmethod load_from_config(config)#

Creates an instance of SecureBinaryX from configuration.

The method parses the configuration to extract all necessary parameters for creating a SecureBinaryX instance, including family revision, image type, signature provider, and commands.

Parameters:

config (Config) – Input standard configuration containing SBX parameters.

Return type:

Self

Returns:

Instance of Secure Binary X class.

load_tphsm(tphsm, offset=0)#

Load TPHSM blob from binary data.

This method parses the provided TPHSM binary data and stores it as a TpHsmBlob object in the instance.

Parameters:
  • tphsm (bytes) – TPHSM binary data to be parsed.

  • offset (int) – Starting offset in the binary data, defaults to 0.

Return type:

None

classmethod parse(data, offset=0)#

Parse object from bytes array.

Parameters:
  • data (bytes) – Input bytes array to parse the object from.

  • offset (int) – Starting offset in the bytes array, defaults to 0.

Raises:

NotImplementedError – Not yet implemented.

Return type:

Self

Returns:

Parsed object instance.

update_header()#

Update SBx header.

Updates the SB header with current command information from sb_commands. This method synchronizes the header metadata to reflect the current state of the command sequence.

Return type:

None

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of SBx class members.

Return type:

None

class spsdk.sbfile.sbx.images.SecureBinaryXCommands(family, hash_type, timestamp=None, encryption_provider=<spsdk.sbfile.utils.encryption_provider.NoEncryption object>)#

Bases: SecureBinary31Commands

SBX (Secure Binary X) commands container for NXP MCU provisioning.

This class manages and processes SBX format commands used in secure provisioning operations for NXP microcontrollers, extending the SB3.1 command functionality.

Variables:
  • FEATURE – Database feature identifier for SBX operations.

  • SB_COMMANDS_NAME – Human-readable name for SBX command format.

Initialize container for SB3.1 commands.

Parameters:
  • family (FamilyRevision) – Device family and revision information.

  • hash_type (EnumHashAlgorithm) – Hash algorithm type used in commands binary block.

  • timestamp (Optional[int]) – Timestamp used for encryption, defaults to current timestamp if None.

  • encryption_provider (EncryptionProvider) – Encryption provider instance, defaults to NoEncryption.

Raises:

SPSDKValueError – Invalid hash type not supported by the family.

FEATURE = 'sbx'#
SB_COMMANDS_NAME = 'SBX'#
class spsdk.sbfile.sbx.images.SecureBinaryXHeader(firmware_version, description=None, timestamp=None, image_type=SecureBinaryXType.OEM_PROVISIONING, flags=0)#

Bases: BaseClass

SecureBinary X file header representation.

This class manages the header structure for SecureBinary X (SBx) files, handling metadata such as firmware version, timestamps, image types, and descriptions. It provides functionality for creating, validating, and serializing SBx headers according to the NXP secure binary format specification.

Variables:
  • HEADER_FORMAT – Binary format string for header structure.

  • HEADER_SIZE – Total size of the header in bytes.

  • MAGIC – Magic bytes identifier for SBx files.

  • FORMAT_VERSION – Version of the SBx format.

  • DESCRIPTION_LENGTH – Maximum length for description field.

  • BLOCK_SIZE – Size of data blocks in the SBx file.

Initialize the SecureBinary X Header.

Parameters:
  • firmware_version (int) – Firmware version number.

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None.

  • timestamp (Optional[int]) – Timestamp (number of seconds since Jan 1st, 2000), if None use current time.

  • image_type (SecureBinaryXType) – Type of the SB file, defaults to OEM_PROVISIONING.

  • flags (int) – Flags for SBx file, defaults to 0.

BLOCK_SIZE = 292#
DESCRIPTION_LENGTH = 16#
FORMAT_VERSION = '1.0'#
HEADER_FORMAT = '<4s2H3LQ3L16s'#
HEADER_SIZE = 140#
MAGIC = b'sbvx'#
export()#

Export the SB file to bytes.

Converts the SBX image header structure into a binary representation using the defined header format and packing all header fields according to the specification.

Return type:

bytes

Returns:

Exported header bytes containing the complete SBX image header structure.

classmethod parse(data, offset=0)#

Parse binary data into SecureBinaryXHeader.

This method deserializes binary data according to the SBX header format and creates a SecureBinaryXHeader instance with the parsed values.

Parameters:
  • data (bytes) – Binary data containing the SBX header.

  • offset (int) – Offset in the data where parsing should start.

Raises:

SPSDKError – Unable to parse SBX Header due to invalid magic, version, or block size.

Return type:

Self

Returns:

Parsed SecureBinaryXHeader instance.

update(commands)#

Updates the volatile fields in header by real commands.

Parameters:

commands (SecureBinaryXCommands) – SBx Commands block to extract data from.

Return type:

None

validate()#

Validate the settings of SBx header class members.

Performs comprehensive validation of all required SBx header attributes including flags, block count, block size, image type, firmware version, timestamp, block 0 total length, and image description to ensure they meet the SBx format requirements.

Raises:

SPSDKError – Invalid configuration of SBx header blob class members.

Return type:

None

class spsdk.sbfile.sbx.images.SecureBinaryXType(value)#

Bases: Enum

Secure Binary X container type enumeration.

This enumeration defines the different types of Secure Binary X containers used in SPSDK for various provisioning and deployment scenarios.

NXP_PROVISIONING = 1#
OEM = 3#
OEM_PROVISIONING = 2#
class spsdk.sbfile.sbx.images.TpHsmBlob(tphsm_header, signature=None, hmac_key=None)#

Bases: BaseClass

TP HSM (Trusted Provisioning Hardware Security Module) blob container.

This class represents a cryptographically secured blob used in trusted provisioning operations. It combines a TP HSM header with HMAC-based authentication to ensure data integrity and authenticity during secure provisioning workflows.

Variables:
  • FORMAT – Binary format string for blob structure.

  • SIZE – Total size of the blob in bytes.

Initialize TPHSM blob with header and authentication.

Creates a new TPHSM blob instance with the provided header and either a signature or HMAC key for authentication. If HMAC key is provided, it will be used to generate the signature from the header data.

Parameters:
  • tphsm_header (Union[TpHsmBlobHeader, bytes]) – TPHSM header object or raw header bytes.

  • signature (Optional[bytes]) – Pre-computed blob signature bytes, optional.

  • hmac_key (Optional[str]) – Hexadecimal string representation of HMAC key for signature generation, optional.

Raises:

SPSDKError – When neither signature nor HMAC key is provided.

FORMAT = '<20s32s'#
SIZE = 52#
export()#

Export TP HSM blob in binary form.

Converts the TP HSM blob object into its binary representation by combining the header and signature components.

Return type:

bytes

Returns:

Binary representation of the TP HSM blob.

classmethod parse(data, offset=0)#

Parse TpHsmBlob object from bytes array.

Parameters:
  • data (bytes) – Input data as bytes to parse the TpHsmBlob from.

  • offset (int) – The offset of input data (default: 0).

Return type:

TpHsmBlob

Returns:

TpHsmBlob instance parsed from the data.

Raises:

SPSDKParsingError – Unexpected size or signature of data.

class spsdk.sbfile.sbx.images.TpHsmBlobHeader(version=1, blob_type=0, oem_enc_data=b'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00')#

Bases: BaseClass

TP HSM blob header for secure provisioning operations.

This class represents and manages the header structure for TP HSM (TrustProvisioning Hardware Security Module) blobs, providing functionality to create, parse, and export binary header data with version control and OEM encryption support.

Variables:
  • FORMAT – Binary format string for header structure.

  • SIZE – Total size of the header in bytes.

  • SIGNATURE – Expected signature for header validation.

Initialize TpHsmBlob instance.

Parameters:
  • version (int) – Blob version number.

  • blob_type (int) – Type of the HSM blob.

  • oem_enc_data (bytes) – OEM encryption data, defaults to 16 zero bytes.

Raises:

SPSDKError – When there is invalid version.

FORMAT = '<2BH16s'#
SIGNATURE = b'cert'#
SIZE = 20#
export()#

Export TP HSM block header in binary form.

Serializes the TP HSM block header into its binary representation using the defined format structure.

Return type:

bytes

Returns:

Binary representation of the TP HSM block header.

classmethod parse(header_data, offset=0)#

Parse TpHsmBlobHeader object from bytes array.

Parameters:
  • header_data (bytes) – Input data as bytes to parse the header from.

  • offset (int) – The offset of input data (default: 0).

Return type:

TpHsmBlobHeader

Returns:

TpHsmBlobHeader instance.

Raises:

SPSDKParsingError – Unexpected size or signature of data.

SBFile Version X - DEVHSM#

SPSDK DevHSM SBx file generation utilities.

This module provides functionality for generating initialization SBx files for development Hardware Security Module (HSM) operations within the SPSDK framework.

class spsdk.sbfile.sbx.devhsm.DevHsmSBx(mboot, family, oem_share_input=None, oem_enc_master_share_input=None, sbx=None, workspace=None, initial_reset=False, final_reset=True, buffer_address=None, info_print=None)#

Bases: DevHsm

Device HSM provisioning manager for SBx containers.

This class handles the complete device Hardware Security Module (HSM) provisioning workflow for SBx secure binary containers, including OEM share management, data encryption, signing operations, and secure binary creation.

Variables:
  • SUB_FEATURE – Identifier for the DevHSM SBx sub-feature.

  • DEVBUFF_GEN_MASTER_ENC_SHARE_OUTPUT_SIZE – Buffer size for master encryption share output.

  • DEVBUFF_SB_SIGNATURE_SIZE – Buffer size for secure binary signature data.

Initialize device HSM class for creating provisioned SBX files.

The DeviceHSM class provides functionality to create secure binary files using device-based Hardware Security Module capabilities.

Parameters:
  • mboot (McuBoot) – mBoot communication interface for device interaction.

  • family (FamilyRevision) – Target chip family and revision information.

  • oem_share_input (Optional[bytes]) – OEM share input data, defaults to random 16 bytes if not provided.

  • oem_enc_master_share_input (Optional[bytes]) – OEM encryption master share for recreating security session.

  • sbx (Optional[SecureBinaryX]) – SBX container object to be processed.

  • workspace (Optional[str]) – Optional directory path for storing intermediate results.

  • initial_reset (Optional[bool]) – Whether to reset device before DevHSM SB3 file creation.

  • final_reset (Optional[bool]) – Whether to reset device after DevHSM SB3 file creation.

  • buffer_address (Optional[int]) – Custom buffer address to override the default value.

  • info_print (Optional[Callable]) – Custom function for printing info messages, defaults to built-in print.

Raises:

SPSDKError – When SBX container is not provided or other initialization errors occur.

DEVBUFF_GEN_MASTER_ENC_SHARE_OUTPUT_SIZE = 52#
DEVBUFF_SB_SIGNATURE_SIZE = 32#
SUB_FEATURE: Optional[str] = 'DevHsmSBx'#
create_sb()#

Create provisioning SBX file using device HSM process.

This method orchestrates the complete device HSM workflow to generate a secure provisioning SBX file. The process includes target reset, OEM master share generation/setting, SBX header creation, data encryption, signature generation, and final file composition.

Raises:

SPSDKError – When OEM_SHARE or OEM_ENC_MASTER_SHARE is not provided but required for OEM master share creation.

Return type:

None

encrypt_data_blocks(sbx_header, data_cmd_blocks)#

Encrypt all data blocks using device HSM functionality.

The method writes the SBX header and each data command block to device memory, performs HSM encryption on each block, and retrieves the encrypted results. Temporary files are stored for debugging purposes during the encryption process.

Parameters:
  • sbx_header (bytes) – Unencrypted SBX file header bytes.

  • data_cmd_blocks (list[bytes]) – List of unencrypted SBX file command blocks.

Raises:

SPSDKError – Memory write/read operation failure or HSM encryption failure.

Return type:

list[bytes]

Returns:

List of encrypted command blocks from device.

export()#

Get the final SB file.

Return type:

bytes

Returns:

Final SB file in bytes.

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)#

Create the list of validation schemas for DevHSM configuration.

The method builds validation schemas by combining family-specific schemas, DevHSM common configuration schemas, and SBX-related schemas. It also updates the buffer address and removes OEM encryption share properties as needed.

Parameters:

family (FamilyRevision) – Family description containing chip family and revision information.

Return type:

list[dict[str, Any]]

Returns:

List of validation schema dictionaries for configuration validation.

classmethod load_from_config(config, mboot=None, info_print=None)#

Load the class from configuration.

Creates a DEVHSM SB3.1 instance from the provided configuration, extracting all necessary parameters including family settings, cryptographic keys, and operational parameters.

Parameters:
  • config (Config) – DEVHSM configuration file containing all setup parameters.

  • mboot (Optional[McuBoot]) – Optional mBoot interface object for device communication.

  • info_print (Optional[Callable]) – Optional callback function for printing informational messages.

Raises:

SPSDKError – When mboot parameter is not provided.

Return type:

Self

Returns:

Configured DEVHSM SB3.1 class instance.

oem_generate_master_share(oem_share_input=None)#

Generate on device Encrypted OEM master share outputs.

This method creates an encrypted OEM master share by writing the input to device memory, executing the HSM create session command, and reading back the encrypted share output.

Parameters:

oem_share_input (Optional[bytes]) – OEM input data used as randomization seed, if None uses default.

Raises:

SPSDKError – If OEM share input is not defined, memory operations fail, or HSM command execution fails.

Return type:

tuple[bytes, bytes, bytes]

Returns:

Tuple containing encrypted OEM share, empty bytes, and empty bytes.

oem_set_master_share(oem_seed=None, enc_oem_share=None)#

Set OEM Master share on the device.

This method configures the OEM (Original Equipment Manufacturer) master share on the target device using either an OEM seed or an encrypted OEM share.

Parameters:
  • oem_seed (Optional[bytes]) – Optional seed value for generating the OEM master share.

  • enc_oem_share (Optional[bytes]) – Optional encrypted OEM share data to be set on device.

Raises:

SPSDKNotImplementedError – Method is not yet implemented.

Return type:

bytes

sign_data_blob(data_to_sign)#

Sign data blob using HSM encryption.

This method writes the input data to device buffer, performs HSM encryption signing operation, and retrieves the generated signature from the device.

Parameters:

data_to_sign (bytes) – Input data bytes to be signed by HSM.

Raises:

SPSDKError – If writing data to device fails, HSM signing command fails, or reading signature from device fails.

Return type:

bytes

Returns:

Data blob signature (64 bytes).

SBFile Version C#

SPSDK Secure Binary Container (SBc) module.

This module provides the SBc implementation for SPSDK sbfile package, offering secure boot container functionality with command parsing and execution capabilities.

class spsdk.sbfile.sbc.CmdErase(address, length, memory_id=0)

Bases: BaseCmd

SB3.1 erase command for memory operations.

This command erases a specified address range in memory, with the erase operation automatically rounded up to the sector size. The command supports different memory types through memory ID specification.

Variables:

CMD_TAG – Command tag identifier for erase operations.

Initialize SB3.1 command with address, length and memory parameters.

Parameters:
  • address (int) – Target memory address for the command operation

  • length (int) – Number of bytes to be processed by the command

  • memory_id (int) – Identifier of the target memory interface, defaults to 0

CMD_TAG = (1, 'erase')
export()

Export command as bytes array.

Serializes the command into a binary format suitable for secure boot file generation. The exported data includes the base command data followed by memory ID and padding.

Return type:

bytes

Returns:

Binary representation of the command.

property export_length: int

Get export length.

Calculate the total length of the exported command data, including the base command size and additional bytes for memory ID and padding.

Returns:

The length of the exported command data in bytes.

get_config_context(data_path='./')

Create configuration for the ERASE command.

This method generates a configuration dictionary containing the command’s properties and settings, including memory address, length, and memory ID. The ERASE command erases a specified memory region, with the operation being rounded up to the sector size for the specified memory.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)

Load configuration from dictionary.

Creates command objects from configuration data including address, size, and memory ID.

Parameters:

config (Config) – Configuration object containing command parameters.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)

Parse command from bytes array.

This method deserializes a CmdErase command from its binary representation, extracting the address, length, and memory ID while validating padding fields.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command

Return type:

Self

Returns:

CmdErase instance parsed from the input data

Raises:

SPSDKError – Invalid padding in the command data

class spsdk.sbfile.sbc.CmdExecute(address)

Bases: BaseCmd

Address will be the jump-to address.

Initialize Command with specified address.

Parameters:

address (int) – Memory address where the command will be executed.

CMD_TAG = (3, 'execute')
get_config_context(data_path='./')

Create configuration for the EXECUTE command.

This method generates a configuration dictionary containing the command’s properties and settings, including the address to jump to for execution. The EXECUTE command triggers execution at a specified address, which is typically used to start running code after it has been loaded into memory.

Parameters:

data_path (str) – Path to store any data files (not used for this command).

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)

Load configuration from dictionary.

Creates a list of command objects based on the provided configuration data.

Parameters:

config (Config) – Configuration object containing command fields.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

classmethod parse(data)

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

SPSDKError – Invalid data format or parsing error

Return type:

Self

Returns:

CmdExecute instance created from parsed data

class spsdk.sbfile.sbc.CmdLoad(address, data, memory_id=0, compress=False)

Bases: CmdLoadBase

Data to write follows the range header.

Initialize Load command with specified parameters.

Parameters:
  • address (int) – Target memory address where data will be loaded

  • data (bytes) – Binary data to be loaded into memory

  • memory_id (int) – Target memory identifier (default: 0)

  • compress (bool) – Enable data compression for the load operation (default: False)

CMD_TAG = (2, 'load')
get_config_context(data_path='./')

Create configuration for the LOAD command.

This method generates a configuration dictionary containing the command’s properties and settings, including address, memory ID, and data representation. The LOAD command writes data to a specified memory address, which is essential for programming firmware, configuration parameters, or other data into device memory.

Parameters:

data_path (str) – Path to store any data files that might be created for large data.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod load_from_config(config)

Load configuration from dictionary and create command objects.

Creates one or more command objects based on the configuration. When compression is enabled, the data is split into sector-aligned chunks and multiple commands are created.

Parameters:

config (Config) – Configuration object with command fields including address, memoryId, data source, compression settings, and sector size.

Return type:

list[Self]

Returns:

List of command objects loaded from configuration.

Raises:

SPSDKValueError – Address not aligned to sector size when compression is enabled.

class spsdk.sbfile.sbc.CmdLoadKeyBlob(offset, data, key_wrap_id, plain_input=False)

Bases: BaseCmd

SB3.1 command for loading encrypted key blobs into device memory.

This command handles the secure loading of wrapped key material using NXP customer KEK (Key Encryption Key) for both internal and external secure keys. The command supports different key wrap versions and provides family-specific key ID resolution.

Variables:
  • CMD_TAG – Command identifier for load key blob operation.

  • FORMAT – Binary format string for command serialization.

Initialize SB3.1 command with key wrapping parameters.

Parameters:
  • offset (int) – Input offset for the command execution.

  • data (bytes) – Wrapped key blob data to be processed.

  • key_wrap_id (int) – Key wrap identifier (NXP_CUST_KEK_INT_SK = 16, NXP_CUST_KEK_EXT_SK = 17).

  • plain_input (bool) – Whether the input data is in plain format, defaults to False.

CMD_TAG = (10, 'loadKeyBlob')
FORMAT = '<L2H2L'
class KeyTypes(value)

Bases: Enum

SB3.1 key type enumeration for customer KEK configurations.

This enumeration defines the available key types for NXP customer Key Encryption Key (KEK) configurations in SB3.1 secure boot files, supporting both internal and external key storage options.

NXP_CUST_KEK_EXT_SK = 2
NXP_CUST_KEK_INT_SK = 1
export()

Export command as bytes array.

Serializes the command into a binary format according to the SB3.1 specification. The exported data includes command header with TAG, address, key wrap ID, length, and command-specific tag, followed by the actual data payload. The result is aligned to 16-byte boundary with zero padding.

Return type:

bytes

Returns:

Binary representation of the command ready for SB3.1 file inclusion.

property export_length: int

Calculate the total export length including the command header and data.

This property returns the total size in bytes that the command will occupy when exported to binary format, including both the fixed-size command header and any variable-length data payload. The result is aligned to 16-byte boundary.

Returns:

Total length in bytes of the exported command.

get_config_context(data_path='./')

Create configuration for the LOAD_KEY_BLOB command.

This method generates a configuration dictionary containing the command’s properties and settings, including offset, key wrap ID, and the key blob data. The key blob data is stored in a separate binary file for better management and security.

Parameters:

data_path (str) – Path where the key blob file will be stored.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod get_key_id(family, key_name)

Get key ID based on family and key name.

The method retrieves the appropriate key identifier by looking up the chip family database and determining the correct key wraps version to use for the specified key type.

Parameters:
  • family (FamilyRevision) – Chip family revision to determine key mapping.

  • key_name (KeyTypes) – Key type, either NXP_CUST_KEK_INT_SK or NXP_CUST_KEK_EXT_SK.

Raises:

SPSDKValueError – Unsupported key wraps version found in database.

Return type:

int

Returns:

Integer value representing the key identifier.

property length: int

Get data length.

Returns:

Length of the data in bytes.

classmethod load_from_config(config)

Load configuration from dictionary to create command objects.

The method processes configuration data including offset, wrapping key ID, family revision, and input data format. It handles special cases for YAML boolean conversion and supports both hexadecimal and binary input formats.

Parameters:

config (Config) – Configuration object with command fields including offset, wrappingKeyId, family information, plainInput format, and input file path.

Return type:

list[Self]

Returns:

List containing single command object loaded from configuration.

Raises:

SPSDKValueError – When plainInput field is not a string type.

classmethod parse(data)

Parse command from bytes array.

Deserializes a CmdLoadKeyBlob command from its binary representation by extracting the CMPA offset, key wrap ID, and key blob data.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command

Raises:

struct.error – If data format is invalid or insufficient data provided

Return type:

Self

Returns:

CmdLoadKeyBlob instance with parsed parameters

class spsdk.sbfile.sbc.CmdSectionHeader(length, section_uid=1, section_type=1)

Bases: BaseClass

SB3.1 command section header representation.

This class represents a section header for SB3.1 secure boot file commands, providing functionality to create, parse, and export section header data with section UID, type, and length information.

Variables:
  • FORMAT – Binary format string for section header structure.

  • SIZE – Size of the section header in bytes.

Initialize Commands section with specified parameters.

Parameters:
  • length (int) – Length of the commands section in bytes.

  • section_uid (int) – Unique identifier for the section, defaults to 1.

  • section_type (int) – Type identifier for the section, defaults to 1.

FORMAT = '<4L'
SIZE = 16
export()

Export command as bytes.

Serializes the command data into binary format using the predefined FORMAT structure.

Return type:

bytes

Returns:

Binary representation of the command containing section UID, type, length and padding.

classmethod parse(data)

Parse command from bytes array.

The method deserializes a CmdSectionHeader object from binary data by unpacking the section UID, section type, and length fields according to the defined FORMAT.

Parameters:

data (bytes) – Input data as bytes array containing the serialized command.

Raises:

SPSDKError – Raised when FORMAT is bigger than length of the data.

Return type:

Self

Returns:

CmdSectionHeader object parsed from the input data.

class spsdk.sbfile.sbc.EnumCmdTag(tag, label, description=None)

Bases: SpsdkEnum

SB3.1 command tag enumeration.

This enumeration defines all supported command tags used in SB3.1 secure boot files. Each command tag represents a specific operation that can be executed during the secure boot process, such as memory operations, cryptographic functions, and system control commands.

CALL = (4, 'call')
CHECK_LC = (15, 'checkLifecycle')
CONFIGURE_MEMORY = (11, 'configureMemory')
COPY = (8, 'copy')
ERASE = (1, 'erase')
EXECUTE = (3, 'execute')
FILL_MEMORY = (12, 'fillMemory')
FW_VERSION_CHECK = (13, 'checkFwVersion')
LOAD = (2, 'load')
LOAD_CMAC = (7, 'loadCMAC')
LOAD_HASH_LOCKING = (9, 'loadHashLocking')
LOAD_KEY_BLOB = (10, 'loadKeyBlob')
NONE = (0, 'NONE')
PROGRAM_FUSES = (5, 'programFuses')
PROGRAM_IFR = (6, 'programIFR')
RESET = (14, 'reset')
WRITE_IFR = (16, 'writeIFR')
label: str
tag: int
spsdk.sbfile.sbc.parse_command(data)

Parse command from bytes array.

Parses a command structure from the provided bytes data by extracting and validating the command tag, then creating the appropriate command object based on the tag type.

Parameters:

data (bytes) – Input data as bytes array containing the command structure.

Raises:
Return type:

object

Returns:

Parsed command object of the appropriate type.

SBFile Version C - images#

SPSDK Secure Binary Container (SBC) image generation and management.

This module provides functionality for creating and handling Secure Binary Container images, including header management, command processing, and binary generation for secure boot applications across NXP MCU portfolio.

class spsdk.sbfile.sbc.images.SecureBinaryC(family, firmware_version, commands, description=None, image_type=6, flags=1)#

Bases: FeatureBaseClass

Secure Binary Container (SBC) image generator for NXP MCUs.

This class provides functionality to create, validate, and export Secure Binary Container images used for secure boot and firmware updates across NXP’s MCU portfolio. It manages the SBC header, commands, and overall image structure according to the SBC specification.

Variables:

FEATURE – Database manager feature identifier for SBC functionality.

Constructor for Secure Binary vC data container.

Parameters:
  • family (FamilyRevision) – The MCU/MPU family and revision information.

  • firmware_version (int) – Firmware version number.

  • commands (SecureBinaryCCommands) – Secure Binary C commands container.

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None.

  • image_type (int) – Secure Binary C type identifier, defaults to 6.

  • flags (int) – Flags for SB file configuration, defaults to 1.

FEATURE: str = 'sbc'#
export()#

Generate binary output of SBc file.

The method validates the SBc file structure and exports it as a complete binary format including header, hash, signature placeholder, and command data blocks.

Raises:

SPSDKError – If validation of the SBc file structure fails.

Return type:

bytes

Returns:

Content of SBc file in bytes.

export_header(final_hash=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')#

Export SBc header without signature for encryption on device.

The method combines the SB header data with a final hash to create a plain header suitable for device-side encryption processing.

Parameters:

final_hash (bytes) – Hash of the next block to append to header data.

Return type:

bytes

Returns:

Plain header without signature in bytes.

get_config(data_path='./')#

Create configuration of the Feature.

Parameters:

data_path (str) – Path to directory containing configuration data files.

Raises:

SPSDKNotImplementedError – Method not implemented in base class.

Return type:

Config

classmethod get_validation_schemas(family, include_test_configuration=False)#

Create the list of validation schemas for SBC configuration.

The method retrieves and combines validation schemas from different sources including MBI, SBC, and general family schemas. It supports optional inclusion of test configuration schemas for development purposes.

Parameters:
  • family (FamilyRevision) – Family description containing chip family and revision information.

  • include_test_configuration (bool) – Add also testing configuration schemas.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas for SBC configuration validation.

classmethod load_from_config(config)#

Creates an instance of SecureBinaryC from configuration.

Loads SecureBinaryC object with all necessary components including family revision, commands, firmware version and description from the provided configuration.

Parameters:

config (Config) – Input standard configuration containing SBC parameters.

Return type:

Self

Returns:

Instance of Secure Binary C class.

classmethod parse(data, offset=0)#

Parse object from bytes array.

Parameters:
  • data (bytes) – Input bytes array to parse the object from.

  • offset (int) – Starting offset in the bytes array, defaults to 0.

Raises:

NotImplementedError – Not yet implemented.

Return type:

Self

Returns:

Parsed object instance.

update_header()#

Update SBc header.

Updates the SB header with information from the current SB commands collection. This method synchronizes the header metadata to reflect the state of all commands that will be included in the secure boot file.

Return type:

None

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of SBc class members.

Return type:

None

class spsdk.sbfile.sbc.images.SecureBinaryCCommands(family, hash_type, timestamp=None, encryption_provider=<spsdk.sbfile.utils.encryption_provider.NoEncryption object>)#

Bases: SecureBinary31Commands

Secure Binary Container (SBc) commands manager.

This class manages SBc format commands for secure binary containers, extending the SB3.1 command functionality with SBc-specific features and command processing capabilities.

Variables:
  • FEATURE – Database feature identifier for SBC operations.

  • SB_COMMANDS_NAME – Display name for SBc command format.

Initialize container for SB3.1 commands.

Parameters:
  • family (FamilyRevision) – Device family and revision information.

  • hash_type (EnumHashAlgorithm) – Hash algorithm type used in commands binary block.

  • timestamp (Optional[int]) – Timestamp used for encryption, defaults to current timestamp if None.

  • encryption_provider (EncryptionProvider) – Encryption provider instance, defaults to NoEncryption.

Raises:

SPSDKValueError – Invalid hash type not supported by the family.

FEATURE = 'sbc'#
SB_COMMANDS_NAME = 'SBc'#
class spsdk.sbfile.sbc.images.SecureBinaryCHeader(firmware_version=1, description=None, timestamp=None, image_type=6, flags=1)#

Bases: BaseClass

SecureBinary C Header for SB3.1 format files.

This class represents the header structure for Secure Binary version 3.1 files, managing header metadata including firmware version, description, timestamps, and format-specific parameters required for secure provisioning operations.

Variables:
  • MAGIC – Magic bytes identifier for SB3.1 format (b”sbv3”).

  • FORMAT_VERSION – Supported format version string (“3.1”).

  • HEADER_SIZE – Total size of the header structure in bytes.

  • BLOCK_SIZE – Standard block size for SB3.1 files.

  • CERT_OFFSET – Offset position for certificate data in the header.

Initialize the SecureBinary C Header.

Parameters:
  • firmware_version (int) – Firmware version

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None

  • timestamp (Optional[int]) – Timestamp (number of seconds since Jan 1st, 2000), if None use current time

  • image_type (int) – type of the SB file, defaults to OEM_PROVISIONING

  • flags (int) – Flags for SBc file, defaults to 0

BLOCK_SIZE = 292#
CERT_OFFSET = 92#
DESCRIPTION_LENGTH = 16#
FORMAT_VERSION = '3.1'#
HEADER_FORMAT = '<4s2H3LQ4L16s'#
HEADER_SIZE = 92#
MAGIC = b'sbv3'#
MANIFEST_SIZE = 172#
export()#

Export the SB file to bytes.

Return type:

bytes

Returns:

Exported header bytes

classmethod parse(data, offset=0)#

Parse binary data into SecureBinaryC Header.

This method unpacks binary data according to the SBC header format and creates a new instance with the parsed values. It validates the magic number, version, and block size to ensure the data represents a valid SBC header.

Parameters:
  • data (bytes) – Binary data containing the SBC header.

  • offset (int) – Offset in the data where parsing should start.

Raises:

SPSDKError – Unable to parse SBc Header due to invalid magic, version, or block size.

Return type:

Self

Returns:

New instance of SecureBinaryC Header with parsed data.

update(commands)#

Updates the volatile fields in header by real commands.

Parameters:

commands (SecureBinaryCCommands) – SBc Commands block

Return type:

None

validate()#

Validate the settings of SBC header class members.

Performs comprehensive validation of all SBC header attributes including flags, block count, block size, firmware version, timestamp, total length, and description. Ensures all required fields are properly set with valid values.

Raises:

SPSDKError – Invalid configuration of SBC header class members.

Return type:

None

class spsdk.sbfile.sbc.images.SecureBinaryCHeaderV2(firmware_version=1, description=None, timestamp=None, image_type=6, flags=1)#

Bases: SecureBinaryCHeader

Secure Binary C Header Version 2.

This class represents version 2 of the SBC header with extended functionality and additional validation rules compared to the base SecureBinaryCHeader.

Initialize the SecureBinary C Header.

Parameters:
  • firmware_version (int) – Firmware version

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None

  • timestamp (Optional[int]) – Timestamp (number of seconds since Jan 1st, 2000), if None use current time

  • image_type (int) – type of the SB file, defaults to OEM_PROVISIONING

  • flags (int) – Flags for SBc file, defaults to 0

MANIFEST_SIZE = 188#

SBFile Version C - DEVHSM#

SPSDK DevHSM SBc file generation utilities.

This module provides functionality for generating initialization SBc files for DevHSM (Development Hardware Security Module) operations within the SPSDK framework.

class spsdk.sbfile.sbc.devhsm.DevHsmSBc(mboot, family, oem_share_input=None, sbc=None, workspace=None, initial_reset=False, final_reset=True, buffer_address=None, info_print=None)#

Bases: DevHsm

Device HSM provisioning handler for Secure Binary Container (SBc) format.

This class manages the complete device HSM provisioning workflow for SBc containers, including OEM share generation, key wrapping, data signing, encryption, and final SBc file creation with hardware security module integration.

Variables:
  • SIGNATURE_SIZE – Size of signature data in bytes (16).

  • KEY_SIZE – Encryption key size in bytes (24).

  • KEY_WRAPPING_OVERHEAD – Additional bytes required for key wrapping (8).

Initialization of device HSM class. It’s designed to create provisioned sbc file.

Parameters:
  • mboot (McuBoot) – mBoot communication interface.

  • family (FamilyRevision) – chip family

  • oem_share_input (Optional[bytes]) – OEM share input - either the provided value or a randomly generated 16 bytes seed

  • sbc (Optional[SecureBinaryC]) – SBC container.

  • workspace (Optional[str]) – Optional folder to store middle results.

  • initial_reset (Optional[bool]) – Reset device before DevHSM creation of SBc file.

  • final_reset (Optional[bool]) – Reset device after DevHSM creation of SBc file.

  • buffer_address (Optional[int]) – Override the default buffer address.

  • info_print (Optional[Callable]) – Method for printing out info messages. Default: built-in print

Raises:

SPSDKError – In case of any problem.

KEY_SIZE = 24#
KEY_WRAPPING_OVERHEAD = 8#
SIGNATURE_SIZE = 16#
SUB_FEATURE: Optional[str] = 'DevHsmSBc'#
create_sb()#

Do device hsm process to create provisioning SBC file.

Return type:

None

encrypt_data_blocks(cust_fw_enc_key, sbc_header, data_cmd_blocks)#

Encrypt all data blocks on device.

Parameters:
  • sbc_header (bytes) – Un Encrypted sbc file header.

  • cust_fw_enc_key (bytes) – Firmware encryption key.

  • data_cmd_blocks (list[bytes]) – List of un-encrypted sbc file command blocks.

Raises:

SPSDKError – In case of any vulnerability.

Return type:

list[bytes]

Returns:

List of encrypted command blocks on device.

export()#

Get the Final SB file.

Return type:

bytes

Returns:

Final SB file in bytes.

generate_key(key_type, address, key_name=None)#

Generate on device key of provided type.

Parameters:
  • key_type (TrustProvOemKeyType) – Type of generated key.

  • address (int) – Keyblob output address.

  • key_name (Optional[str]) – Optional name for storing temporary files.

Raises:

SPSDKError – In case of any vulnerability.

Return type:

bytes

Returns:

Key.

get_config(data_path='./')#

Create configuration of the Feature.

Return type:

Config

classmethod get_validation_schemas(family)#

Create the list of validation schemas.

Parameters:

family (FamilyRevision) – Family description.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

classmethod load_from_config(config, mboot=None, info_print=None)#

Load the class from configuration.

Parameters:
  • config (Config) – DEVHSM configuration file

  • mboot (Optional[McuBoot]) – mBoot object

  • info_print (Optional[Callable]) – Optional info print method

Return type:

Self

Returns:

DEVHSM SBc class

oem_generate_master_share(oem_share_input)#

Generate on device Encrypted OEM master share outputs.

Parameters:

oem_share_input (bytes) – OEM input (randomize seed)

Raises:

SPSDKError – In case of any vulnerability.

Return type:

tuple[bytes, bytes, bytes]

Returns:

Tuple with OEM generate master share outputs.

oem_set_master_share(oem_seed=None, enc_oem_share=None)#

Set OEM Master share on the device.

Raises:

SPSDKNotImplementedError – Always raised as this operation is not supported.

Return type:

bytes

sign_data_blob(data_to_sign, key)#

Get HSM encryption sign for data blob.

Parameters:
  • data_to_sign (bytes) – Input data to sign.

  • key (bytes) – Signing key.

Raises:

SPSDKError – In case of any error.

Return type:

bytes

Returns:

Data blob signature (64 bytes).

wrap_key(key_data)#

Wrap key data for secure transmission.

Parameters:

key_data (bytes) – Raw key data to be wrapped

Return type:

bytes

Returns:

Wrapped key data

Raises:

SPSDKError – If wrapping fails or returning None

SBFile - miscellaneous functions#

SPSDK SBFile miscellaneous utilities and helper functions.

This module provides utility functions and classes for SBFile operations, including version handling, block size management, and timestamp operations.

SBFile - DEVHSM#

SPSDK Development HSM base class module.

This module provides the abstract base class for Development Hardware Security Module implementations used in SPSDK for secure provisioning operations. The DevHsm class serves as the foundation for various HSM implementations, defining the common interface and basic functionality required for secure key management and cryptographic operations in development environments.

class spsdk.sbfile.devhsm.devhsm.DevHsm(family, workspace=None)#

Bases: FeatureBaseClass

SPSDK Device Hardware Security Module (HSM) base class.

This abstract base class provides the foundation for Device HSM operations across NXP MCU portfolio, managing secure provisioning workflows including master share generation, key management, and secure boot file creation. It handles device buffer operations and provides standardized interface for HSM-related security functions.

Variables:
  • DEVBUFF_SIZE – Size of the device buffer (256 bytes).

  • DEVBUFF_GEN_MASTER_SHARE_INPUT_SIZE – Input buffer size for master share generation.

  • DEVBUFF_GEN_MASTER_ENC_SHARE_OUTPUT_SIZE – Output buffer size for encrypted share.

  • DEVBUFF_GEN_MASTER_ENC_MASTER_SHARE_OUTPUT_SIZE – Output buffer size for encrypted master share.

  • DEVBUFF_GEN_MASTER_CUST_CERT_PUK_OUTPUT_SIZE – Output buffer size for customer certificate public key.

  • DEVBUFF_HSM_GENKEY_KEYBLOB_SIZE – Size of HSM generated key blob.

  • DEVBUFF_HSM_GENKEY_KEYBLOB_PUK_SIZE – Size of HSM generated key blob public key.

  • DEVBUFF_CUST_MK_SK_KEY_SIZE – Size of customer master key.

  • DEVBUFF_DATA_BLOCK_SIZE – Size of data block buffer.

  • DEVBUFF_SB_SIGNATURE_SIZE – Size of secure boot signature.

  • RESET_TIMEOUT – Timeout for device reset operations in milliseconds.

Device HSM base class constructor.

Initialize Device HSM with specified chip family and optional workspace directory. Creates workspace directory if it doesn’t exist.

Parameters:
  • family (FamilyRevision) – Chip family and revision information.

  • workspace (Optional[str]) – Optional path to workspace directory for HSM operations.

Raises:

OSError – When workspace directory cannot be created.

DEVBUFF_CUST_MK_SK_KEY_SIZE = 32#
DEVBUFF_DATA_BLOCK_SIZE = 256#
DEVBUFF_GEN_MASTER_CUST_CERT_PUK_OUTPUT_SIZE = 64#
DEVBUFF_GEN_MASTER_ENC_MASTER_SHARE_OUTPUT_SIZE = 64#
DEVBUFF_GEN_MASTER_ENC_SHARE_OUTPUT_SIZE = 48#
DEVBUFF_GEN_MASTER_SHARE_INPUT_SIZE = 16#
DEVBUFF_HSM_GENKEY_KEYBLOB_PUK_SIZE = 64#
DEVBUFF_HSM_GENKEY_KEYBLOB_SIZE = 48#
DEVBUFF_SB_SIGNATURE_SIZE = 64#
DEVBUFF_SIZE = 256#
FEATURE: str = 'devhsm'#
F_BUFFER = 'comm_buffer'#
F_DEVHSM = 'devhsm'#
RESET_TIMEOUT = 500#
command_order()#

Get command order configuration for the device family.

Retrieves the boolean configuration value that determines the command ordering behavior for the specific device family from the database.

Return type:

bool

Returns:

True if command ordering is enabled for the family, False otherwise.

abstract create_sb()#

Create SB file.

This method generates a Secure Binary (SB) file using the configured DevHSM parameters and writes it to the specified output location.

Raises:

SPSDKError – If SB file creation fails due to configuration or processing errors.

Return type:

None

get_devbuff_base_address(index)#

Get devbuff base address for specified index.

Calculates the base address for a device buffer at the given index by adding the index offset to the base devbuff address.

Parameters:

index (int) – Device buffer index (0-9).

Raises:

SPSDKValueError – Invalid index provided (must be 0-9).

Return type:

int

Returns:

Base address of the device buffer at specified index.

get_devbuff_wrapped_cust_mk_sk_key_size()#

Get the size of wrapped customer master key SK.

This method retrieves the size configuration for the device buffer wrapped customer master key Symmetric Key from the database.

Return type:

int

Returns:

Size of wrapped customer master key SK in bytes.

get_keyblob_offset()#

Get keyblob offset based on family.

Return type:

int

Returns:

The keyblob offset value from the database configuration.

get_keyblob_position()#

Get keyblob position from database.

Return type:

int

Returns:

Position of the keyblob command in the database as an integer value.

static get_oem_share_input(binary=None, search_paths=None)#

Get OEM share input data from file.

Loads 16-byte OEM share input data from either a text file containing hex string or a binary file.

Parameters:
  • binary (Optional[str]) – Path to binary or text file containing OEM share input data.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None.

Return type:

bytes

Returns:

16-byte binary array loaded from file.

Raises:

SPSDKValueError – When invalid input value is recognized.

abstract oem_generate_master_share(oem_share_input)#

Generate OEM master share on device with encryption.

This method processes the OEM share input to generate encrypted master share outputs using the device’s hardware security module capabilities.

Parameters:

oem_share_input (bytes) – Input data for OEM share generation.

Return type:

tuple[bytes, bytes, bytes]

Returns:

Tuple containing three encrypted master share output components.

abstract oem_set_master_share(oem_seed=None, enc_oem_share=None)#

Set OEM Master share on the device.

This method configures the OEM (Original Equipment Manufacturer) master share on the target device using either an OEM seed or an encrypted OEM share.

Parameters:
  • oem_seed (Optional[bytes]) – Optional seed value for generating the OEM master share.

  • enc_oem_share (Optional[bytes]) – Optional encrypted OEM share data to be set on device.

Return type:

bytes

Returns:

Response data from the device after setting the master share.

classmethod parse(data)#

Parse object from bytes array.

Parameters:

data (bytes) – Object data in bytes format to be parsed.

Raises:

SPSDKNotImplementedError – If parsing is not implemented.

Return type:

Self

store_temp_res(file_name, data, group=None)#

Store temporary files into workspace.

The method saves data to a file in the workspace directory. If a group is specified, the file will be stored in a corresponding subfolder that will be created if it doesn’t exist.

Parameters:
  • file_name (str) – Name of file to store the data.

  • data (bytes) – Binary data to store in the file.

  • group (Optional[str]) – Optional subfolder name for organizing files, defaults to None.

Return type:

None

SBFile - DEVHSM utils#

SPSDK DevHSM utility functions for secure boot file processing.

This module provides utility functions for working with DevHSM (Development Hardware Security Module) implementations across different secure boot file formats in SPSDK.

spsdk.sbfile.devhsm.utils.get_devhsm_class(family)#

Get DevHSM class based on chip family.

The method retrieves the appropriate DevHSM class implementation by checking the database for supported sub-features of the given family and returning the corresponding class type.

Parameters:

family (FamilyRevision) – Chip family revision to get DevHSM class for.

Raises:

SPSDKError – If DevHSM is not supported for the specified family.

Return type:

Type[Union[DevHsmSB4, DevHsmSB31, DevHsmSBx, DevHsmSBc]]

Returns:

DevHSM class type that supports the given family.