SBFile Module API

Contents

SBFile Module API#

Module implementing SBFile.

SBFile Version 1#

Module implementing SBFile version 1.

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

Bases: object

Version in format #.#.#, where # is BCD number (1-4 digits).

Initialize BcdVersion3.

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

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

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

Raises:

SPSDKError – Invalid version

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

Convert string to BcdVersion instance.

Parameters:

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

Return type:

BcdVersion3

Returns:

BcdVersion3 instance

Raises:

SPSDKError – If format is not valid

property nums: Sequence[int]#

Return array of version numbers: [major, minor, service].

static to_version(input_version)#

Convert different input formats into BcdVersion3 instance.

Parameters:

input_version (Union[BcdVersion3, str]) – either directly BcdVersion3 or string

Raises:

SPSDKError – Raises when the 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 1.x.

Initialize BootSectionV1.

Parameters:
  • section_id (int) – unique section ID, 32-bit int

  • flags (SecureBootFlagsV1) – see SecureBootFlagsV1

append(cmd)#

Append command.

Parameters:

cmd (CmdBaseClass) – to be added

Return type:

None

property bootable: bool#

Return whether section is bootable.

property cmd_size: int#

Return size of the binary representation of the commands.

property commands: Sequence[CmdBaseClass]#

Return sequence of all commands in the section.

export()#

Return binary representation of the class (serialization).

Return type:

bytes

property flags: SecureBootFlagsV1#

Return section flags.

classmethod parse(data)#

Deserialization from binary format.

Parameters:

data (bytes) – to be parsed

Return type:

Self

Returns:

the parsed instance

property rom_last_tag: bool#

ReturnROM_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.

property section_id: int#

Return unique ID of the section, 32 number.

property size: int#

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

update()#

Update settings.

Return type:

None

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

Bases: CmdBaseClass

Command Call.

The call statement is used for inserting a bootloader command that executes a function from one of the files that are loaded into the memory.

Initialize Command Call.

property address: int#

Return command’s address.

property argument: int#

Return command’s argument.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Call object

Raises:

SPSDKError – If incorrect header tag

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

Bases: CmdBaseClass

Command Erase class.

Initialize Command Erase.

property address: int#

Return command’s address.

property flags: int#

Return command’s flag.

property length: int#

Return command’s count.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Erase object

Raises:

SPSDKError – If incorrect header tag

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

Bases: CmdBaseClass

Command Fill class.

Initialize Command Fill.

Parameters:
  • address (int) – to write data

  • pattern (int) – data to be written

  • length (Optional[int]) – length of data to be filled, defaults to 4

Raises:

SPSDKError – Raised when size is not aligned to 4 bytes

PADDING_VALUE = 0#
property address: int#

Return address of the command Fill.

export()#

Return command in binary form (serialization).

Return type:

bytes

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Fill object

Raises:

SPSDKError – If incorrect header tag

property pattern: bytes#

Return binary data to fill.

property raw_size: int#

Calculate raw size of header.

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

Bases: CmdBaseClass

Command Jump class.

Initialize Command Jump.

property address: int#

Return address of the command Jump.

property argument: int#

Return command’s argument.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Jump object

Raises:

SPSDKError – If incorrect header tag

property spreg: int | None#

Return command’s Stack Pointer.

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

Bases: CmdBaseClass

Command Load. The load statement is used to store data into the memory.

Initialize CMD Load.

property address: int#

Return address in target processor to load data.

export()#

Export command as binary.

Return type:

bytes

property flags: int#

Return command’s flag.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

CMD Load object

Raises:
property raw_size: int#

Return aligned size of the command including header and data.

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

Bases: CmdBaseClass

Command to configure certain memory.

Initialize CmdMemEnable.

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

property address: int#

Return command’s address.

property flags: int#

Return command’s flag.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Memory Enable object

Raises:

SPSDKError – If incorrect header tag

property size: int#

Return command’s size.

class spsdk.sbfile.sb1.CmdNop#

Bases: CmdBaseClass

Command NOP class.

Initialize Command Nop.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

CMD Nop object

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

Command Program class.

Initialize CMD Prog.

property address: int#

Return address in target processor to program data.

property data_word1: int#

Return data word 1.

property data_word2: int#

Return data word 2.

property flags: int#

Return command’s flag.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

parsed command object

Raises:

SPSDKError – If incorrect header tag

class spsdk.sbfile.sb1.CmdReset#

Bases: CmdBaseClass

Command Reset class.

Initialize Command Reset.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Cmd Reset object

Raises:

SPSDKError – If incorrect header tag

class spsdk.sbfile.sb1.CmdTag#

Bases: CmdBaseClass

Command TAG class.

It is also used as header for boot section for SB file 1.x.

Initialize Command Tag.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

parsed instance

Raises:

SPSDKError – When there is incorrect header tag

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

Bases: SpsdkEnum

Flags for SectionHeader.

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

SB file 1.x.

Initialize Secure Boot Image V1.x.

Parameters:
  • version (str) – string in format #.# Major version of the boot image format, currently 1. Minor version of the boot image format, currently 1 or 2.

  • flags (int) – for the header, 0 by default: Flags associated with the entire image.

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

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

  • drive_tag (int) – For header: identifier for the disk drive or partition containing this image.

  • dek (Optional[bytes]) – DEK key for encrypted SB file; this is not supported yet

  • mac (Optional[bytes]) – MAC for encrypted SB file, this is not supported yet

  • digest (bytes) – SHA-1 digest of all fields of the header (it will be updated before export anyway) The first 16 bytes (of 20 total) also act as the initialization vector for CBC-encrypted regions.

  • timestamp (Optional[datetime]) – datetime of the file creation, use None for current date/time Fixed value should be used only for regression testing to generate same results

append(section)#

Add section into the SB file.

Parameters:

section (BootSectionV1) – to be added

Return type:

None

export(header_padding8=None, auth_padding=None)#

Serialization to binary form.

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:

Exported the instance into binary data

Raises:
property first_boot_section_id: int#

Return id of first boot section.

classmethod parse(data)#

Convert binary data into the instance (deserialization).

Parameters:

data (bytes) – given binary data to be converted

Return type:

Self

Returns:

converted instance

Raises:
property sections: Sequence[BootSectionV1]#

Return sequence of all sections on the SB file.

property size: int#

Return size of the binary representation in bytes.

update()#

Update content.

Return type:

None

validate()#

Validate settings.

Raises:

SPSDKError – If the settings is not consistent

Return type:

None

SBFile Version 1 commands#

Commands for SBFile.

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

Parse SB V1.x command from binary format.

Parameters:

data (bytes) – Input data as bytes

Return type:

CmdBaseClass

Returns:

parsed command object

Raises:

SPSDKError – Raised when there is unsupported command

SBFile Version 1 headers#

Secure Boot Header.

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

Bases: CmdTag

Header of boot section derived from command TAG.

Note: Command TAG was reused to save some code in Boot ROM

Initialize BootSectionHeaderV1.

Parameters:
  • section_id (int) – unique section ID, 32-bit int

  • flags (SecureBootFlagsV1) – see SecureBootFlagsV1

SIZE = 16#
property bootable: bool#

Return whether section is bootable.

property flags: SecureBootFlagsV1#

Return section flags.

property num_blocks: int#

Return size of the section in number of cipher blocks.

classmethod parse(data)#

Parse from bytes into BootSectionHeaderV1 object.

Return type:

Self

property rom_last_tag: bool#

Return 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.

property section_id: int#

Return unique ID of the section, 32 number.

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/row in section header table in in SB file V1.x.

Initialize SectionHeaderItemV1.

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 SectionHeaderV1Flags

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

Return whether section is bootable.

export()#

Return serialization to binary format.

Return type:

bytes

property flags: int#

Return flags, see SectionHeaderV1Flags.

classmethod parse(data)#

Parse binary data into the instance (deserialization).

Parameters:

data (bytes) – to be parsed

Return type:

Self

Returns:

the new instance

Raises:

SPSDKError – If size is not sufficient

property size: int#

Return size of exported data in bytes.

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

Bases: SpsdkEnum

Flags for SectionHeader.

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 Boot Header V1.

Initialize SecureBootHeaderV1.

Parameters:
  • version (str) – of the format: 1.0 or 1.1 or 1.2

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

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

  • 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 all fields of the header, 20 bytes The first 16 bytes (of 20 total) also act as the initialization vector for CBC-encrypted regions.

  • timestamp (Optional[datetime]) – datetime of the file creation, use None for current date/time Fixed value should be used only for regression testing to generate same results

Raises:

SPSDKError – Invalid header version

export(padding8=None)#

Serialization to binary form.

Parameters:

padding8 (Optional[bytes]) – 8 padding bytes used for in the header, None to use random bytes This value shall be used only for regression testing to generate same results

Return type:

bytes

Returns:

Exported object into bytes

property first_boot_tag_block: int#

Return first boot tag block.

property key_dictionary_block: int#

Return key dictionary block.

classmethod parse(data)#

Convert binary data into the instance (deserialization).

Parameters:

data (bytes) – given binary data to be decoded

Return type:

Self

Returns:

the instance of secure boot header v1

Raises:
  • SPSDKError – Raised when there is insufficient size

  • SPSDKError – Raised when there is invalid signature

  • SPSDKError – Raised when there is unexpected signature

property size: int#

Return size of the header in bytes.

SBFile Version 1 images#

Secure Boot Image Class.

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

SB file 1.x.

Initialize Secure Boot Image V1.x.

Parameters:
  • version (str) – string in format #.# Major version of the boot image format, currently 1. Minor version of the boot image format, currently 1 or 2.

  • flags (int) – for the header, 0 by default: Flags associated with the entire image.

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

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

  • drive_tag (int) – For header: identifier for the disk drive or partition containing this image.

  • dek (Optional[bytes]) – DEK key for encrypted SB file; this is not supported yet

  • mac (Optional[bytes]) – MAC for encrypted SB file, this is not supported yet

  • digest (bytes) – SHA-1 digest of all fields of the header (it will be updated before export anyway) The first 16 bytes (of 20 total) also act as the initialization vector for CBC-encrypted regions.

  • timestamp (Optional[datetime]) – datetime of the file creation, use None for current date/time Fixed value should be used only for regression testing to generate same results

append(section)#

Add section into the SB file.

Parameters:

section (BootSectionV1) – to be added

Return type:

None

export(header_padding8=None, auth_padding=None)#

Serialization to binary form.

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:

Exported the instance into binary data

Raises:
property first_boot_section_id: int#

Return id of first boot section.

classmethod parse(data)#

Convert binary data into the instance (deserialization).

Parameters:

data (bytes) – given binary data to be converted

Return type:

Self

Returns:

converted instance

Raises:
property sections: Sequence[BootSectionV1]#

Return sequence of all sections on the SB file.

property size: int#

Return size of the binary representation in bytes.

update()#

Update content.

Return type:

None

validate()#

Validate settings.

Raises:

SPSDKError – If the settings is not consistent

Return type:

None

SBFile Version 1 sections#

Boot Selection for SB file.

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

Bases: BaseClass

Boot Section for SB file 1.x.

Initialize BootSectionV1.

Parameters:
  • section_id (int) – unique section ID, 32-bit int

  • flags (SecureBootFlagsV1) – see SecureBootFlagsV1

append(cmd)#

Append command.

Parameters:

cmd (CmdBaseClass) – to be added

Return type:

None

property bootable: bool#

Return whether section is bootable.

property cmd_size: int#

Return size of the binary representation of the commands.

property commands: Sequence[CmdBaseClass]#

Return sequence of all commands in the section.

export()#

Return binary representation of the class (serialization).

Return type:

bytes

property flags: SecureBootFlagsV1#

Return section flags.

classmethod parse(data)#

Deserialization from binary format.

Parameters:

data (bytes) – to be parsed

Return type:

Self

Returns:

the parsed instance

property rom_last_tag: bool#

ReturnROM_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.

property section_id: int#

Return unique ID of the section, 32 number.

property size: int#

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

update()#

Update settings.

Return type:

None

SBFile Version 2#

Module implementing SB2 and SB2.1 File.

SBFile Version 2 commands#

Commands used by SBFile module.

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

Bases: BaseClass

Base class for all commands.

Initialize CmdBase.

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()#

Return object serialized into bytes.

Return type:

bytes

property header: CmdHeader#

Return command header.

property raw_size: int#

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

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

Bases: CmdBaseClass

Command Call.

The call statement is used for inserting a bootloader command that executes a function from one of the files that are loaded into the memory.

Initialize Command Call.

property address: int#

Return command’s address.

property argument: int#

Return command’s argument.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Call object

Raises:

SPSDKError – If incorrect header tag

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

Bases: CmdBaseClass

Command Erase class.

Initialize Command Erase.

property address: int#

Return command’s address.

property flags: int#

Return command’s flag.

property length: int#

Return command’s count.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Erase object

Raises:

SPSDKError – If incorrect header tag

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

Bases: CmdBaseClass

Command Fill class.

Initialize Command Fill.

Parameters:
  • address (int) – to write data

  • pattern (int) – data to be written

  • length (Optional[int]) – length of data to be filled, defaults to 4

Raises:

SPSDKError – Raised when size is not aligned to 4 bytes

PADDING_VALUE = 0#
property address: int#

Return address of the command Fill.

export()#

Return command in binary form (serialization).

Return type:

bytes

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Fill object

Raises:

SPSDKError – If incorrect header tag

property pattern: bytes#

Return binary data to fill.

property raw_size: int#

Calculate raw size of header.

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

Bases: BaseClass

SBFile command header.

Initialize header.

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

Calculate CRC for the header data.

export()#

Export command header as bytes.

Return type:

bytes

classmethod parse(data)#

Parse command header from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

CMDHeader object

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

Bases: CmdBaseClass

Command Jump class.

Initialize Command Jump.

property address: int#

Return address of the command Jump.

property argument: int#

Return command’s argument.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Jump object

Raises:

SPSDKError – If incorrect header tag

property spreg: int | None#

Return command’s Stack Pointer.

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

Bases: CmdKeyStoreBackupRestore

Command to backup keystore from non-volatile memory.

Initialize CmdKeyStoreBackupRestore.

Parameters:
  • address (int) – 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

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

Bases: CmdBaseClass

Shared, abstract implementation for key-store backup and restore command.

Initialize CmdKeyStoreBackupRestore.

Parameters:
  • address (int) – 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.

abstract classmethod cmd_id()#

Return command ID.

Raises:

NotImplementedError – Derived class has to implement this method

Return type:

EnumCmdTag

property controller_id: int#

Return controller ID of the memory to backup key-store or source memory to load key-store back.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

CmdKeyStoreBackupRestore object

Raises:

SPSDKError – When there is invalid header tag

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

Bases: CmdKeyStoreBackupRestore

Command to restore keystore into non-volatile memory.

Initialize CmdKeyStoreBackupRestore.

Parameters:
  • address (int) – 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

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

Bases: CmdBaseClass

Command Load. The load statement is used to store data into the memory.

Initialize CMD Load.

property address: int#

Return address in target processor to load data.

export()#

Export command as binary.

Return type:

bytes

property flags: int#

Return command’s flag.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

CMD Load object

Raises:
property raw_size: int#

Return aligned size of the command including header and data.

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

Bases: CmdBaseClass

Command to configure certain memory.

Initialize CmdMemEnable.

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

property address: int#

Return command’s address.

property flags: int#

Return command’s flag.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Command Memory Enable object

Raises:

SPSDKError – If incorrect header tag

property size: int#

Return command’s size.

class spsdk.sbfile.sb2.commands.CmdNop#

Bases: CmdBaseClass

Command NOP class.

Initialize Command Nop.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

CMD Nop object

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

Command Program class.

Initialize CMD Prog.

property address: int#

Return address in target processor to program data.

property data_word1: int#

Return data word 1.

property data_word2: int#

Return data word 2.

property flags: int#

Return command’s flag.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

parsed command object

Raises:

SPSDKError – If incorrect header tag

class spsdk.sbfile.sb2.commands.CmdReset#

Bases: CmdBaseClass

Command Reset class.

Initialize Command Reset.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

Cmd Reset object

Raises:

SPSDKError – If incorrect header tag

class spsdk.sbfile.sb2.commands.CmdTag#

Bases: CmdBaseClass

Command TAG class.

It is also used as header for boot section for SB file 1.x.

Initialize Command Tag.

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

parsed instance

Raises:

SPSDKError – When there is incorrect header tag

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

Bases: CmdBaseClass

FW Version Check command class.

Validates version of secure or non-secure firmware. The command fails if version is < expected.

Initialize CmdVersionCheck.

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

  • version (int) – to be checked

Raises:

SPSDKError – If invalid version check type

classmethod parse(data)#

Parse command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

Self

Returns:

parsed command object

Raises:

SPSDKError – If incorrect header tag

property type: VersionCheckType#

Return type of the check version, see VersionCheckType enumeration.

property version: int#

Return minimal version expected.

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

Bases: SpsdkEnum

Command tags.

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

Section flags.

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

Bases: SpsdkEnum

Select type of the version check: either secure or non-secure firmware to be checked.

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.

Parameters:

mem_id (int) – memory ID

Return type:

int

Returns:

device ID

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

Get group ID from memory ID.

Parameters:

mem_id (int) – memory ID

Return type:

int

Returns:

group ID

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

Get memory ID from device ID and group ID.

Parameters:
  • device_id (int) – device ID

  • group_id (int) – group ID

Return type:

int

Returns:

memory ID

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

Parse SB 2.x command from bytes.

Parameters:

data (bytes) – Input data as bytes

Return type:

CmdBaseClass

Returns:

parsed command object

Raises:

SPSDKError – Raised when there is unsupported command provided

SBFile Version 2 headers#

Image header.

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

Image Header V2 class.

Initialize Image Header Version 2.x.

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

  • timestamp (Optional[datetime]) – value requested in the test; None to use current value

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

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

Export object into bytes.

Parameters:

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

Return type:

bytes

Returns:

Exported binary representation

Raises:
  • SPSDKError – Raised when format is incorrect

  • SPSDKError – Raised when length of padding is incorrect

  • SPSDKError – Raised when length of header is incorrect

flags_desc()#

Return flag description.

Return type:

str

classmethod parse(data)#

Deserialization from binary form.

Parameters:

data (bytes) – binary representation

Return type:

Self

Returns:

parsed instance of the header

Raises:

SPSDKError – Unable to parse data

SBFile Version 2 images#

Boot Image V2.0, V2.1.

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

Boot Image V2.0 class.

Initialize Secure Boot Image V2.0.

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

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

  • 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

  • sections (BootSectionV2) – Boot sections

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

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#

Return certificate block; None if SB file not signed or block not assigned yet.

property cert_header_size: int#

Return image raw size (not aligned) for certificate header.

property dek: bytes#

Data encryption key.

export(padding=None)#

Export image object.

Parameters:

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

Return type:

bytes

Returns:

Exported bytes

Raises:
  • SPSDKError – Raised when there are no boot sections or is not signed or private keys are missing

  • SPSDKError – Raised when there is invalid dek or mac

  • SPSDKError – Raised when certificate data is not present

  • SPSDKError – Raised when there is invalid certificate block

  • SPSDKError – Raised when there is invalid length of exported data

property header: ImageHeaderV2#

Return image header.

property kek: bytes#

Return key for wrapping DEK and MAC keys.

property mac: bytes#

Message authentication code.

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

Parse image from bytes.

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

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

Return type:

Self

Returns:

parsed image object

Raises:
  • SPSDKError – raised when header is in wrong format

  • SPSDKError – raised when there is invalid header version

  • SPSDKError – raised when signature is incorrect

  • SPSDKError – Raised when kek is empty

  • SPSDKError – raised when header’s nonce is not present

property raw_size: int#

Return image raw size.

property raw_size_without_signature: int#

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

property signed: bool#

Check whether sb is signed + encrypted or only encrypted.

update()#

Update boot image.

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

Boot Image V2.1 class.

Initialize Secure Boot Image V2.1.

Parameters:
  • kek (bytes) – key to wrap DEC and MAC keys

  • 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) – optional advanced parameters for encryption; it is recommended to use default value

  • flags (int) – see flags defined in class.

  • sections (BootSectionV2) – Boot sections

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#

Return certificate block; None if SB file not signed or block not assigned yet.

property cert_header_size: int#

Return image raw size (not aligned) for certificate header.

property dek: bytes#

Data encryption key.

export(padding=None)#

Export image object.

Parameters:

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

Return type:

bytes

Returns:

Exported bytes

Raises:
  • SPSDKError – Raised when there is no boot section to be added

  • SPSDKError – Raised when certificate is not assigned

  • SPSDKError – Raised when private key is not assigned

  • SPSDKError – Raised when private header’s nonce is invalid

  • SPSDKError – Raised when private key does not match certificate

  • SPSDKError – Raised when there is no debug info

classmethod get_advanced_params(config)#

Get advanced test params from configuration.

Parameters:

config (dict[str, Any]) – Input standard configuration.

Return type:

SBV2xAdvancedParams

Returns:

SBV2xAdvancedParams advanced test params

classmethod get_commands_validation_schemas(family=None)#

Create the list of validation schemas.

Parameters:

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

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

classmethod get_config_template(family)#

Generate configuration template.

Parameters:

family (FamilyRevision) – Device family.

Return type:

str

Returns:

Dictionary of individual templates (key is name of template, value is template itself).

static get_supported_families()#

Return list of supported families.

Return type:

list[FamilyRevision]

Returns:

List of supported families.

classmethod get_validation_schemas(family)#

Create the list of validation schemas.

Parameters:

family (FamilyRevision) – Device family

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

property header: ImageHeaderV2#

Return image header.

property kek: bytes#

Return key to wrap DEC and MAC keys.

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)#

Creates an instance of BootImageV21 from configuration.

Parameters:
  • config (Config) – Input standard configuration.

  • key_file_path (Optional[str]) – path to key file.

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

  • signing_certificate_file_paths (Optional[list[str]]) – signing certificate chain.

  • root_key_certificate_paths (Optional[list[str]]) – paths to root key certificate(s) for verifying other certificates. Only 4 root key certificates are allowed, others are ignored. One of the certificates must match the first certificate passed in signing_certificate_file_paths.

  • rkth_out_path (Optional[str]) – output path to hash of hashes of root keys. If set to None, ‘hash.bin’ is created under working directory.

Return type:

Self

Returns:

Instance of Secure Binary V2.1 class

property mac: bytes#

Message authentication code.

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

Parse image from bytes.

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

  • offset (int) – The offset of input data

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

  • plain_sections (bool) – Sections are not encrypted; this is used only for debugging, not supported by ROM code

Return type:

BootImageV21

Returns:

BootImageV21 parsed object

Raises:
  • SPSDKError – raised when header is in incorrect format

  • SPSDKError – raised when signature is incorrect

  • SPSDKError – Raised when kek is empty

  • SPSDKError – raised when header’s nonce not present”

classmethod parse_sb21_config(config_path, external_files=None)#

Create lexer and parser, load the BD file content and parse it.

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

Return type:

Config

Returns:

Dictionary with parsed configuration.

property raw_size: int#

Return image raw size (not aligned).

property signed: bool#

Return flag whether SB file is signed.

update()#

Update BootImageV21.

Return type:

None

static validate_header(binary)#

Validate SB2.1 header in binary data.

Parameters:

binary (bytes) – Binary data to be validate

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

The class holds advanced parameters for the SB file encryption.

These parameters are used for the tests; for production, use can use default values (random keys + current time)

Initialize SBV2xAdvancedParams.

Parameters:
  • dek (Optional[bytes]) – DEK key

  • mac (Optional[bytes]) – MAC key

  • nonce (Optional[bytes]) – nonce

  • 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#

Return DEK key.

property mac: bytes#

Return MAC key.

property nonce: bytes#

Return NONCE.

property padding: bytes#

Return padding.

property timestamp: datetime#

Return timestamp.

property zero_padding: bool#

Return True if padding is zero, False otherwise.

SBFile Version 2 sections#

Sections within SBfile.

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

Bases: BaseClass

Boot Section V2.

Initialize BootSectionV2.

Parameters:
  • uid (int) – section unique identification

  • commands (CmdBaseClass) – List of commands

  • hmac_count (int) – The number of HMAC entries

  • zero_filling (bool) – If true, the section is zero-filled

HMAC_SIZE = 32#
append(cmd)#

Add command to section.

Return type:

None

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

Export Boot Section object.

Parameters:
  • 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:

bytes

Returns:

Exported bytes

Raises:

SPSDKError – raised when dek, mac, counter have invalid format or no commands

property hmac_count: int#

Number of HMACs.

property is_last: bool#

Check whether the section is the last one.

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

Parse Boot Section from bytes.

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

  • offset (int) – The offset of input data

  • plain_sect (bool) – If the sections are not encrypted; It is used for debugging only, not supported by ROM code

  • 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:

BootSectionV2

Returns:

exported bytes

Raises:

SPSDKError – raised when dek, mac, counter have invalid format

property raw_size: int#

Raw size of section.

property uid: int#

Boot Section UID.

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

Bases: BaseClass

Certificate Section V2 class.

Initialize CertBlockV1.

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

Return certification block.

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

Export Certificate Section object.

Parameters:
  • 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:

bytes

Returns:

Exported bytes

Raises:
  • SPSDKError – raised when dek, mac, counter have invalid format

  • SPSDKError – Raised size of exported bytes is invalid

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

Parse Certificate Section from bytes array.

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.

SBFile Version 3.1.#

SB31 module of sbfile.

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

Bases: BaseCmd

Address will be the address to jump.

Constructor for Command.

Parameters:

address (int) – Input address

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.

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:

CmdCall

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

Bases: BaseCmd

Configure memory.

Constructor for command.

Parameters:
  • address (int) – Input address

  • memory_id (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

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.

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:

CmdConfigureMemory

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.

Constructor for command.

Parameters:
  • address (int) – Input address

  • length (int) – Input length

  • destination_address (int) – Destination address

  • memory_id_from (int) – Memory ID

  • memory_id_to (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

property export_length: int#

Export length of command.

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.

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:

CmdCopy

Raises:

SPSDKError – Invalid padding

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

Bases: BaseCmd

Erase given address range. The erase will be rounded up to the sector size.

Constructor for command.

Parameters:
  • address (int) – Input address

  • length (int) – Input length

  • memory_id (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

property export_length: int#

Get export length.

Returns:

The length of the exported command data

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.

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:

CmdErase

Raises:

SPSDKError – Invalid padding

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

Bases: BaseCmd

Address will be the jump-to address.

Constructor for Command.

Parameters:

address (int) – Input address

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.

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:

CmdExecute

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

Bases: BaseCmd

Fill memory range by pattern.

Constructor for command.

Parameters:
  • address (int) – Input address

  • length (int) – Input length

  • pattern (int) – Pattern for fill memory with

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

Export command as bytes.

Return type:

bytes

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.

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:

CmdErase

Raises:

SPSDKError – Invalid padding

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

Bases: CmdLoadBase

Data to write follows the range header.

Constructor for command.

Parameters:
  • address (int) – Address for the load command

  • data (bytes) – Data to load

  • memory_id (int) – Memory ID

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.

Parameters:

config (Config) – Dictionary with configuration fields.

Return type:

list[Self]

Returns:

Command object loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

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

Bases: CmdLoadBase

Load cmac. ROM is calculating cmac from loaded data.

Constructor for command.

Parameters:
  • address (int) – Address for the load command

  • data (bytes) – Data to load

  • memory_id (int) – Memory ID

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.

Parameters:

config (Config) – Dictionary with configuration fields.

Return type:

list[Self]

Returns:

Command object loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

classmethod parse(data)#

Parse command from bytes array.

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

Load hash. ROM is calculating hash.

Constructor for command.

Parameters:
  • address (int) – Address for the load command

  • data (bytes) – Data to load

  • memory_id (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

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

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.

Raises:

SPSDKError – Invalid configuration field.

classmethod parse(data)#

Parse command from bytes array.

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.CmdLoadKeyBlob(offset, data, key_wrap_id, plain_input=False)#

Bases: BaseCmd

Load key blob.

Constructor for command.

Parameters:
  • offset (int) – Input offset

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

  • data (bytes) – Wrapped key blob

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

Bases: Enum

KeyTypes for NXP_CUST_KEK_INT_SK, NXP_CUST_KEK_EXT_SK.

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

Export command as bytes.

Return type:

bytes

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.

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.

Parameters:
  • family (FamilyRevision) – chip family

  • key_name (KeyTypes) – NXP_CUST_KEK_INT_SK or NXP_CUST_KEK_EXT_SK

Return type:

int

Returns:

integer value representing key

property length: int#

Get data length.

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:

CmdLoadKeyBlob

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

Bases: CmdLoadBase

Address will be address of fuse register.

Constructor for Command.

Parameters:
  • address (int) – Input address

  • data (bytes) – Input data

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.

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:

CmdProgFuses

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

Bases: CmdLoadBase

Address will be the address into the IFR region.

Constructor for Command.

Parameters:
  • address (int) – Input address

  • data (bytes) – Input data 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) – 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:

CmdProgFuses

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

Bases: BaseClass

Create section header.

Constructor for Commands section.

Parameters:
  • section_uid (int) – Input uid

  • section_type (int) – Input type

  • length (int) – Input length

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

Export command as bytes.

Return type:

bytes

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

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

Return type:

Self

Returns:

CmdSectionHeader

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

Bases: SpsdkEnum

Contains commands tags.

CALL = (4, 'call')#
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')#
spsdk.sbfile.sb31.parse_command(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:
Return type:

object

Returns:

object

SBFile Version 3.1. functions#

File including helping functions.

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

Bases: SpsdkEnum

Modes for Key derivation.

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

Engine for generating derived keys.

Initialize the KeyDerivator.

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/256bits)

  • kdk_access_rights (int) – KeyDerivationKey access rights

get_block_key(block_number)#

Derive key for particular block.

Return type:

bytes

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

Return data with leading zeros.

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

  • return_size (int)

Return type:

bytes

Returns:

bytes

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

Return data with trailing zeros.

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

  • return_size (int)

Return type:

bytes

Returns:

bytes

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

Derive encryption AES key for given block.

Parameters:
  • kdk (bytes) – Key Derivation Key

  • block_number (int) – Block number

  • key_length (int) – Required key length (128/256)

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

Return type:

bytes

Returns:

AES key for given block

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

Derive the Key Derivation Key.

Parameters:
  • pck (bytes) – Part Common Key

  • timestamp (int) – Timestamp for KDK derivation

  • key_length (int) – Requested key length (128/256b)

  • kdk_access_rights (int) – KDK access rights (0-3)

Return type:

bytes

Returns:

Key Derivation Key

SBFile Version 3.1. commands#

Module for creation commands.

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

Bases: BaseClass

Functions for creating cmd intended for inheritance.

Constructor for Commands header.

Parameters:
  • address (int) – Input address

  • length (int) – Input length

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

Get address.

export()#

Export command as bytes.

Return type:

bytes

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

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.

Return type:

Config

Returns:

Configuration object with command-specific settings.

classmethod header_parse(data)#

Parse header command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:
  • SPSDKError – Raised if tag is not equal to required TAG

  • SPSDKError – Raised if cmd is not equal EnumCmdTag

Return type:

tuple[int, int]

Returns:

Tuple

classmethod header_parse_raw(data)#

Parse header command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:
  • SPSDKError – Raised if tag is not equal to required TAG

  • SPSDKError – Raised if cmd is not equal EnumCmdTag

Return type:

tuple[int, int, int]

Returns:

Tuple

property length: int#

Get length.

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.

Raises:

NotImplementedError – Derived class has to implement this method

classmethod parse(data)#

Parse object from bytes array.

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.

Constructor for Command.

Parameters:

address (int) – Input address

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.

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:

CmdCall

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

Bases: BaseCmd

Configure memory.

Constructor for command.

Parameters:
  • address (int) – Input address

  • memory_id (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

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.

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:

CmdConfigureMemory

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.

Constructor for command.

Parameters:
  • address (int) – Input address

  • length (int) – Input length

  • destination_address (int) – Destination address

  • memory_id_from (int) – Memory ID

  • memory_id_to (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

property export_length: int#

Export length of command.

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.

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:

CmdCopy

Raises:

SPSDKError – Invalid padding

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

Bases: BaseCmd

Erase given address range. The erase will be rounded up to the sector size.

Constructor for command.

Parameters:
  • address (int) – Input address

  • length (int) – Input length

  • memory_id (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

property export_length: int#

Get export length.

Returns:

The length of the exported command data

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.

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:

CmdErase

Raises:

SPSDKError – Invalid padding

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

Bases: BaseCmd

Address will be the jump-to address.

Constructor for Command.

Parameters:

address (int) – Input address

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.

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:

CmdExecute

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

Bases: BaseCmd

Fill memory range by pattern.

Constructor for command.

Parameters:
  • address (int) – Input address

  • length (int) – Input length

  • pattern (int) – Pattern for fill memory with

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

Export command as bytes.

Return type:

bytes

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.

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:

CmdErase

Raises:

SPSDKError – Invalid padding

class spsdk.sbfile.sb31.commands.CmdFwVersionCheck(value, counter_id)#

Bases: BaseCmd

Check counter value with stored value, if values are not same, SB file is rejected.

Constructor for command.

Parameters:
  • value (int) – Input value

  • counter_id (CounterID) – Counter ID (NONSECURE = 1, SECURE = 2)

CMD_TAG = (13, 'checkFwVersion')#
class CounterID(tag, label, description=None)#

Bases: SpsdkEnum

Counter IDs used by the CmdFwVersionCheck command.

BOOTLOADER = (5, 'bootloader')#
NONE = (0, 'none')#
NONSECURE = (1, 'nonsecure')#
RADIO = (3, 'radio')#
SECURE = (2, 'secure')#
SNT = (4, 'snt')#
export()#

Export command as bytes.

Return type:

bytes

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.

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:

CmdFwVersionCheck

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

Bases: CmdLoadBase

Data to write follows the range header.

Constructor for command.

Parameters:
  • address (int) – Address for the load command

  • data (bytes) – Data to load

  • memory_id (int) – Memory ID

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.

Parameters:

config (Config) – Dictionary with configuration fields.

Return type:

list[Self]

Returns:

Command object loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

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

Bases: BaseCmd

Base class for commands loading data.

Constructor for command.

Parameters:
  • cmd_tag – Command tag for the derived class

  • address (int) – Address for the load command

  • data (bytes) – Data to load

  • memory_id (int) – Memory ID

  • compress (bool) – Compress data

HAS_MEMORY_ID_BLOCK = True#
export()#

Export command as bytes.

Return type:

bytes

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.

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:

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.

Constructor for command.

Parameters:
  • address (int) – Address for the load command

  • data (bytes) – Data to load

  • memory_id (int) – Memory ID

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.

Parameters:

config (Config) – Dictionary with configuration fields.

Return type:

list[Self]

Returns:

Command object loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

classmethod parse(data)#

Parse command from bytes array.

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

Load hash. ROM is calculating hash.

Constructor for command.

Parameters:
  • address (int) – Address for the load command

  • data (bytes) – Data to load

  • memory_id (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

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

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.

Raises:

SPSDKError – Invalid configuration field.

classmethod parse(data)#

Parse command from bytes array.

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.CmdLoadKeyBlob(offset, data, key_wrap_id, plain_input=False)#

Bases: BaseCmd

Load key blob.

Constructor for command.

Parameters:
  • offset (int) – Input offset

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

  • data (bytes) – Wrapped key blob

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

Bases: Enum

KeyTypes for NXP_CUST_KEK_INT_SK, NXP_CUST_KEK_EXT_SK.

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

Export command as bytes.

Return type:

bytes

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.

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.

Parameters:
  • family (FamilyRevision) – chip family

  • key_name (KeyTypes) – NXP_CUST_KEK_INT_SK or NXP_CUST_KEK_EXT_SK

Return type:

int

Returns:

integer value representing key

property length: int#

Get data length.

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:

CmdLoadKeyBlob

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

Bases: CmdLoadBase

Address will be address of fuse register.

Constructor for Command.

Parameters:
  • address (int) – Input address

  • data (bytes) – Input data

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.

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:

CmdProgFuses

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

Bases: CmdLoadBase

Address will be the address into the IFR region.

Constructor for Command.

Parameters:
  • address (int) – Input address

  • data (bytes) – Input data 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) – 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:

CmdProgFuses

class spsdk.sbfile.sb31.commands.CmdReset#

Bases: BaseCmd

Reset command, added for SBx.

Constructor for reset command.

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:

Command object loaded from configuration.

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Return type:

CmdReset

Returns:

CmdReset

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

Bases: BaseClass

Create section header.

Constructor for Commands section.

Parameters:
  • section_uid (int) – Input uid

  • section_type (int) – Input type

  • length (int) – Input length

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

Export command as bytes.

Return type:

bytes

classmethod parse(data)#

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

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

Return type:

Self

Returns:

CmdSectionHeader

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

Parameters:

config (Config) – Dictionary with configuration fields

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.

Parameters:

data (bytes) – Input data as bytes array

Raises:
Return type:

object

Returns:

object

SBFile Version 3.1. images#

Module used for generation SecureBinary V3.1.

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 SB3.1 class.

Constructor for Secure Binary v3.1 data container.

Parameters:
  • family (FamilyRevision) – Device family

  • cert_block (CertBlockV21) – Certification block.

  • firmware_version (int) – Firmware version (must be bigger than current CMPA record).

  • sb_commands (SecureBinary31Commands) – SecureBinary31Commands object containing commands

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None

  • is_nxp_container (bool) – NXP provisioning SB file, defaults to False

  • flags (int) – Flags for SB file, defaults to 0

  • signature_provider (Optional[SignatureProvider]) – Signature provider for final sign of SB3.1 image, defaults to None

  • signature (Optional[bytes]) – Raw signature bytes (if signature_provider is not provided), defaults to None

Raises:

SPSDKError – If neither signature_provider nor signature is provided

FEATURE: str = 'sb31'#
export()#

Generate binary output of SB3.1 file.

Return type:

bytes

Returns:

Content of SB3.1 file in bytes.

classmethod get_commands_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.

get_config(data_path='./')#

Create configuration of the Feature.

Parameters:

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

Return type:

Config

Returns:

Configuration dictionary.

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.

Parameters:

family (FamilyRevision) – Family description.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

get_rkth()#

Get the Root Key Table Hash (RKTH) from the certificate block.

Return type:

bytes

Returns:

RKTH as bytes if available, None otherwise

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)#

Creates an instance of SecureBinary31 from configuration.

Parameters:

config (Config) – Input standard configuration.

Return type:

Self

Returns:

Instance of Secure Binary V3.1 class

classmethod parse(data, family=None, pck=None, kdk_access_rights=0)#

Parse object from bytes array.

Parameters:
  • data (bytes) – Binary data to parse

  • family (Optional[FamilyRevision]) – Family revision information, defaults to None

  • pck (Optional[bytes]) – Part Common Key needed for decryption, defaults to None

  • kdk_access_rights (int) – Key Derivation Key access rights, defaults to 0

Return type:

Self

Returns:

Constructed SecureBinary31 object

Raises:

SPSDKError – When parsing fails or data is invalid

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of SB3.1 class members.

Return type:

None

static validate_header(binary)#

Validate SB3.1 header in binary data.

Parameters:

binary (bytes) – Binary data to be validate

Raises:

SPSDKError – Invalid header of SB3.1 data

Return type:

None

class spsdk.sbfile.sb31.images.SecureBinary31Commands(family, hash_type, is_encrypted=True, pck=None, timestamp=None, kdk_access_rights=None)#

Bases: BaseClass

Blob containing SB3.1 commands.

Initialize container for SB3.1 commands.

Parameters:
  • family (FamilyRevision) – Device family

  • hash_type (EnumHashAlgorithm) – Hash type used in commands binary block

  • is_encrypted (bool) – Indicate whether commands should be encrypted or not, defaults to True

  • pck (Optional[bytes]) – Part Common Key (needed if is_encrypted is True), defaults to None

  • timestamp (Optional[int]) – Timestamp used for encryption (needed if is_encrypted is True), defaults to None

  • kdk_access_rights (Optional[int]) – Key Derivation Key access rights (needed if is_encrypted is True), defaults to None

Raises:
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.

Return type:

None

export()#

Export commands as bytes.

Return type:

bytes

get_cmd_blocks_to_export()#

Export commands as bytes.

Return type:

list[bytes]

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

insert_command(index, command)#

Insert Secure Binary command.

Return type:

None

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.

Parameters:
  • config (Config) – Config object with configuration fields.

  • hash_type (EnumHashAlgorithm) – Hash algorithm to use for command block hashing, defaults to SHA256.

  • timestamp (Optional[int]) – Timestamp value to use in commands, defaults to None (automatic).

  • load_just_commands (bool) – Flag to control whether to load only commands or full configuration, defaults to False.

Return type:

Self

Returns:

Instance of the SecureBinary commands class.

classmethod load_pck(pck_src, search_paths=None)#

Load Part Common Key from source.

Parameters:
  • pck_src (str) – Path or string containing PCK

  • search_paths (Optional[list[str]]) – Optional list of additional search paths

Return type:

bytes

Returns:

Parsed PCK bytes

Raises:

SPSDKError – If PCK cannot be loaded

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.

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.

  • pck (Optional[bytes]) – Part Common Key (bytes) required for decryption.

  • block1_hash (Optional[bytes]) – Hash of the first block (bytes).

  • hash_type (Optional[EnumHashAlgorithm]) – EnumHashAlgorithm specifying the hash algorithm used in the binary data.

  • kdk_access_rights (int) – Key Derivation Key access rights, defaults to 0.

  • timestamp (Optional[int]) – Optional timestamp used for decryption (required for encrypted commands).

Return type:

Self

Returns:

Initialized SecureBinary31Commands object.

Raises:
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.

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.

Return type:

bytes

set_commands(commands)#

Set all Secure Binary commands at once.

Return type:

None

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of SB3.1 commands blob class members.

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

Header of the SecureBinary V3.1 (Block 0).

Initialize the SecureBinary V3.1 Header.

Parameters:
  • hash_type (EnumHashAlgorithm) – Hash type used in commands binary block

  • firmware_version (int) – Firmware version (must be bigger than current CMPA record)

  • 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, 200), 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

DESCRIPTION_LENGTH = 16#
FORMAT_VERSION = '3.1'#
HEADER_FORMAT = '<4s2H3LQ4L16s'#
HEADER_SIZE = 60#
MAGIC = b'sbv3'#
property block_size: int#

Calculate the the data block size.

property cert_block_offset: int#

Calculate the offset to the Certification block.

export()#

Export the SB file to bytes.

Return type:

bytes

Returns:

Packed binary representation of the SB 3.1 header

export_full_block0()#

Export the complete Block 0 data (header + hash + cert block).

This data is used for signature calculation.

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.

Raises:

SPSDKError – Unable to parse SB31 Header.

Return type:

Self

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)#

Updates the volatile fields in header by real commands and certification block data.

Parameters:

commands (SecureBinary31Commands) – SB3.1 Commands block

Return type:

None

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of SB3.1 header blob class members.

Return type:

None

SBFile Version X#

Module used for generation SecureBinary X.

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 SBX class.

Constructor for Secure Binary vX data container.

Parameters:
  • family (FamilyRevision) – The CPU family

  • tphsm_blob (Optional[TpHsmBlob]) – TP HSM blob

  • firmware_version (int) – Firmware version.

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None

  • image_type (SecureBinaryXType) – SecureBinaryXType

  • signature_provider (Optional[SignatureProvider]) – signature provider to final sign of SBX image in case of OEM and NXP_PROVISIONING types

  • flags (int) – Flags for SB file, defaults to 0

FEATURE: str = 'sbx'#
export()#

Generate binary output of SBx file.

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.

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.

Return type:

Config

classmethod get_validation_schemas(family, include_test_configuration=False)#

Create the list of validation schemas.

Parameters:
  • family (FamilyRevision) – Family description.

  • include_test_configuration (bool) – Add also testing configuration schemas.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

property isk_signed: bool#

Return true if SBx is signed by ISK certificate.

classmethod load_from_config(config)#

Creates an instance of SecureBinaryX from configuration.

Parameters:

config (Config) – Input standard configuration.

Return type:

Self

Returns:

Instance of Secure Binary X class

load_tphsm(tphsm, offset=0)#

Load TPHSM blob from binary data.

Parameters:
  • tphsm (bytes) – TPHSM binary data

  • offset (int) – offset, defaults to 0

Return type:

None

classmethod parse(data, offset=0)#

Parse object from bytes array.

Raises:

NotImplementedError – Not yet implemented

Return type:

Self

update_header()#

Update SBx header.

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, is_encrypted=True, pck=None, timestamp=None, kdk_access_rights=None)#

Bases: SecureBinary31Commands

Blob containing SBX commands.

Initialize container for SB3.1 commands.

Parameters:
  • family (FamilyRevision) – Device family

  • hash_type (EnumHashAlgorithm) – Hash type used in commands binary block

  • is_encrypted (bool) – Indicate whether commands should be encrypted or not, defaults to True

  • pck (Optional[bytes]) – Part Common Key (needed if is_encrypted is True), defaults to None

  • timestamp (Optional[int]) – Timestamp used for encryption (needed if is_encrypted is True), defaults to None

  • kdk_access_rights (Optional[int]) – Key Derivation Key access rights (needed if is_encrypted is True), defaults to None

Raises:
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

Header of the SecureBinary X.

Initialize the SecureBinary X 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 (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.

Return type:

bytes

Returns:

Exported header bytes

classmethod parse(data, offset=0)#

Parse binary data into SecureBinaryXHeader.

Raises:

SPSDKError – Unable to parse SBX Header.

Return type:

Self

update(commands)#

Updates the volatile fields in header by real commands.

Parameters:

commands (SecureBinaryXCommands) – SBx Commands block

Return type:

None

validate()#

Validate the settings of class members.

Raises:

SPSDKError – Invalid configuration of SBx header blob class members.

Return type:

None

class spsdk.sbfile.sbx.images.SecureBinaryXType(value)#

Bases: Enum

Type of the Secure Binary X container.

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 blob.

Constructor.

Parameters:
  • tphsm_header (Union[TpHsmBlobHeader, bytes]) – TPHSM header

  • signature (Optional[bytes]) – blob signature

  • hmac_key (Optional[str]) – of the certificate

Raises:

SPSDKError – When there is invalid version

FORMAT = '<20s32s'#
SIZE = 52#
export()#

TP HSM blob in binary form.

Return type:

bytes

classmethod parse(data, offset=0)#

Parse object from bytes array.

Parameters:
  • data (bytes) – Input data as bytes

  • offset (int) – The offset of input data (default: 0)

Return type:

TpHsmBlob

Returns:

Certificate Header instance

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.

Constructor.

Parameters:
  • version (int) – blob version

  • blob_type (int) – type of the HSM blob

  • build_number – of the certificate

Raises:

SPSDKError – When there is invalid version

FORMAT = '<2BH16s'#
SIGNATURE = b'cert'#
SIZE = 20#
export()#

TP HSM block header in binary form.

Return type:

bytes

classmethod parse(header_data, offset=0)#

Parse object from bytes array.

Parameters:
  • header_data (bytes) – Input data as bytes

  • offset (int) – The offset of input data (default: 0)

Return type:

TpHsmBlobHeader

Returns:

Certificate Header instance

Raises:

SPSDKParsingError – Unexpected size or signature of data

SBFile Version X - DEVHSM#

Module is used to generate initialization SBx file.

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

Class to handle device HSM provisioning procedure for SBx.

Initialization of device HSM class. It’s designed to create provisioned sbx file.

Parameters:
  • mboot (McuBoot) – mBoot communication interface.

  • family (FamilyRevision) – chip family

  • oem_share_input (Optional[bytes]) – OEM share input data. Default: random 16 bytes.

  • oem_enc_master_share_input (Optional[bytes]) – Used for setting the OEM share (recreating security session)

  • sbx (Optional[SecureBinaryX]) – SBX container.

  • workspace (Optional[str]) – Optional folder to store middle results.

  • initial_reset (Optional[bool]) – Reset device before DevHSM creation of SB3 file.

  • final_reset (Optional[bool]) – Reset device after DevHSM creation of SB3 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.

DEVBUFF_GEN_MASTER_ENC_SHARE_OUTPUT_SIZE = 52#
DEVBUFF_SB_SIGNATURE_SIZE = 32#
SUB_FEATURE: Optional[str] = 'DevHsmSBx'#
create_sb()#

Do device hsm process to create provisioning SBX file.

Return type:

None

encrypt_data_blocks(sbx_header, data_cmd_blocks)#

Encrypt all data blocks on device.

Parameters:
  • sbx_header (bytes) – Un Encrypted sbx file header.

  • data_cmd_blocks (list[bytes]) – List of un-encrypted sbx 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.

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 SB3.1 class

oem_generate_master_share(oem_share_input=None)#

Generate on device Encrypted OEM master share outputs.

Parameters:

oem_share_input (Optional[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.

Return type:

bytes

sign_data_blob(data_to_sign)#

Get HSM encryption sign for data blob.

Parameters:

data_to_sign (bytes) – Input data to sign.

Raises:

SPSDKError – In case of any error.

Return type:

bytes

Returns:

Data blob signature (64 bytes).

SBFile Version C#

SBc module of sbfile.

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

Bases: BaseCmd

Erase given address range. The erase will be rounded up to the sector size.

Constructor for command.

Parameters:
  • address (int) – Input address

  • length (int) – Input length

  • memory_id (int) – Memory ID

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

Export command as bytes.

Return type:

bytes

property export_length: int

Get export length.

Returns:

The length of the exported command data

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.

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:

CmdErase

Raises:

SPSDKError – Invalid padding

class spsdk.sbfile.sbc.CmdExecute(address)

Bases: BaseCmd

Address will be the jump-to address.

Constructor for Command.

Parameters:

address (int) – Input address

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.

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:

CmdExecute

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

Bases: CmdLoadBase

Data to write follows the range header.

Constructor for command.

Parameters:
  • address (int) – Address for the load command

  • data (bytes) – Data to load

  • memory_id (int) – Memory ID

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.

Parameters:

config (Config) – Dictionary with configuration fields.

Return type:

list[Self]

Returns:

Command object loaded from configuration.

Raises:

SPSDKError – Invalid configuration field.

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

Bases: BaseCmd

Load key blob.

Constructor for command.

Parameters:
  • offset (int) – Input offset

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

  • data (bytes) – Wrapped key blob

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

Bases: Enum

KeyTypes for NXP_CUST_KEK_INT_SK, NXP_CUST_KEK_EXT_SK.

NXP_CUST_KEK_EXT_SK = 2
NXP_CUST_KEK_INT_SK = 1
export()

Export command as bytes.

Return type:

bytes

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.

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.

Parameters:
  • family (FamilyRevision) – chip family

  • key_name (KeyTypes) – NXP_CUST_KEK_INT_SK or NXP_CUST_KEK_EXT_SK

Return type:

int

Returns:

integer value representing key

property length: int

Get data length.

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:

CmdLoadKeyBlob

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

Bases: BaseClass

Create section header.

Constructor for Commands section.

Parameters:
  • section_uid (int) – Input uid

  • section_type (int) – Input type

  • length (int) – Input length

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

Export command as bytes.

Return type:

bytes

classmethod parse(data)

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:

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

Return type:

Self

Returns:

CmdSectionHeader

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

Bases: SpsdkEnum

Contains commands tags.

CALL = (4, 'call')
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')
label: str
tag: int
spsdk.sbfile.sbc.parse_command(data)

Parse command from bytes array.

Parameters:

data (bytes) – Input data as bytes array

Raises:
Return type:

object

Returns:

object

SBFile Version C - images#

Module used for generation SecureBinary X.

class spsdk.sbfile.sbc.images.SecureBinaryC(family, firmware_version, commands, description=None, image_type=6, flags=1)#

Bases: FeatureBaseClass

Secure Binary SBC class.

Constructor for Secure Binary vC data container.

Parameters:
  • family (FamilyRevision) – The CPU family

  • firmware_version (int) – Firmware version

  • description (Optional[str]) – Custom description up to 16 characters long, defaults to None

  • image_type (int) – SecureBinaryCType

  • signature_provider – signature provider to final sign of SBC image in case of OEM and NXP_PROVISIONING types

  • flags (int) – Flags for SB file, defaults to 0

FEATURE: str = 'sbc'#
export()#

Generate binary output of SBc file.

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.

Return type:

bytes

Returns:

plain header without signature in bytes

get_config(data_path='./')#

Create configuration of the Feature.

Return type:

Config

classmethod get_validation_schemas(family, include_test_configuration=False)#

Create the list of validation schemas.

Parameters:
  • family (FamilyRevision) – Family description.

  • include_test_configuration (bool) – Add also testing configuration schemas.

Return type:

list[dict[str, Any]]

Returns:

List of validation schemas.

classmethod load_from_config(config)#

Creates an instance of SecureBinaryC from configuration.

Parameters:

config (Config) – Input standard configuration.

Return type:

Self

Returns:

Instance of Secure Binary C class

classmethod parse(data, offset=0)#

Parse object from bytes array.

Raises:

NotImplementedError – Not yet implemented

Return type:

Self

update_header()#

Update SBc header.

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, is_encrypted=True, pck=None, timestamp=None, kdk_access_rights=None)#

Bases: SecureBinary31Commands

Blob containing SBC commands.

Initialize container for SB3.1 commands.

Parameters:
  • family (FamilyRevision) – Device family

  • hash_type (EnumHashAlgorithm) – Hash type used in commands binary block

  • is_encrypted (bool) – Indicate whether commands should be encrypted or not, defaults to True

  • pck (Optional[bytes]) – Part Common Key (needed if is_encrypted is True), defaults to None

  • timestamp (Optional[int]) – Timestamp used for encryption (needed if is_encrypted is True), defaults to None

  • kdk_access_rights (Optional[int]) – Key Derivation Key access rights (needed if is_encrypted is True), defaults to None

Raises:
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

Header of the SecureBinary X.

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'#
export()#

Export the SB file to bytes.

Return type:

bytes

Returns:

Exported header bytes

classmethod parse(data, offset=0)#

Parse binary data into SecureBinarycHeader.

Raises:

SPSDKError – Unable to parse SBc Header.

Return type:

Self

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 class members.

Raises:

SPSDKError – Invalid configuration of SBc header blob class members.

Return type:

None

SBFile Version C - DEVHSM#

Module is used to generate initialization SBc file.

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

Class to handle device HSM provisioning procedure for SBc.

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#
OEM_SHARE_OUTPUT_SIZE = 48#
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#

Miscellaneous functions in SBFile module.

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

Bases: object

Version in format #.#.#, where # is BCD number (1-4 digits).

Initialize BcdVersion3.

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

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

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

Raises:

SPSDKError – Invalid version

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

Convert string to BcdVersion instance.

Parameters:

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

Return type:

BcdVersion3

Returns:

BcdVersion3 instance

Raises:

SPSDKError – If format is not valid

property nums: Sequence[int]#

Return array of version numbers: [major, minor, service].

static to_version(input_version)#

Convert different input formats into BcdVersion3 instance.

Parameters:

input_version (Union[BcdVersion3, str]) – either directly BcdVersion3 or string

Raises:

SPSDKError – Raises when the format is unsupported

Return type:

BcdVersion3

Returns:

BcdVersion3 instance

class spsdk.sbfile.misc.SecBootBlckSize#

Bases: object

Helper methods allowing to convert size to number of blocks and back.

Note: The class is not intended to be instantiated

BLOCK_SIZE = 16#
static align(size)#

Align given size to block size.

Parameters:

size (int) – in bytes

Return type:

int

Returns:

size aligned up to block size

static align_block_fill_random(data)#

Align block size to cipher block size.

Parameters:

data (bytes) – to be aligned

Return type:

bytes

Returns:

data aligned to cipher block size, filled with random values

static align_block_fill_zeros(data)#

Align block size to cipher block size.

Parameters:

data (bytes) – to be aligned

Return type:

bytes

Returns:

data aligned to cipher block size, filled with random values

static is_aligned(size)#

Whether size is aligned to cipher block size.

Parameters:

size (int) – given size in bytes

Return type:

bool

Returns:

True if yes, False otherwise

static to_num_blocks(size)#

Converts size to number of cipher blocks.

Parameters:

size (int) – to be converted, the size must be aligned to block boundary

Return type:

int

Returns:

corresponding number of cipher blocks

Raises:

SPSDKError – Raised when size is not aligned to block boundary

spsdk.sbfile.misc.pack_timestamp(value)#

Converts datetime to millisecond since 1.1.2000.

Parameters:

value (datetime) – datetime to be converted

Return type:

int

Returns:

number of milliseconds since 1.1.2000 00:00:00; 64-bit integer

Raises:

SPSDKError – When there is incorrect result of conversion

spsdk.sbfile.misc.unpack_timestamp(value)#

Converts timestamp in milliseconds into datetime.

Parameters:

value (int) – number of milliseconds since 1.1.2000 00:00:00; 64-bit integer

Return type:

datetime

Returns:

corresponding datetime

Raises:

SPSDKError – When there is incorrect result of conversion

SBFile - DEVHSM#

Module is used as a baseclass for DEVHSM.

class spsdk.sbfile.devhsm.devhsm.DevHsm(family, workspace=None)#

Bases: FeatureBaseClass

Base class for DEVHSM.

Device HSM base class constructor.

Parameters:

family (FamilyRevision) – chip family

Workspace:

optional path to workspace

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#
DEVBUFF_WRAPPED_CUST_MK_SK_KEY_SIZE = 48#
FEATURE: str = 'devhsm'#
F_BUFFER = 'comm_buffer'#
F_DEVHSM = 'devhsm'#
RESET_TIMEOUT = 500#
command_order()#

Update command order based on family.

Return type:

bool

abstract create_sb()#

Create SB file.

Return type:

None

get_devbuff_base_address(index)#

Get devbuff base address.

Return type:

int

get_keyblob_offset()#

Update keyblob offset based on family.

Return type:

int

get_keyblob_position()#

Get keyblob position from database.

Return type:

int

static get_oem_share_input(binary=None, search_paths=None)#

Get binary from text or binary file.

Parameters:
  • binary (Optional[str]) – Path to binary file.

  • search_paths (Optional[list[str]]) – List of paths where to search for the file, defaults to None

Return type:

bytes

Returns:

Binary array loaded from file.

Raises:

SPSDKValueError – When invalid input value is recognized.

abstract oem_generate_master_share(oem_share_input)#

Generate on device Encrypted OEM master share outputs.

Return type:

tuple[bytes, bytes, bytes]

abstract oem_set_master_share(oem_seed=None, enc_oem_share=None)#

Set OEM Master share on the device.

Return type:

bytes

classmethod parse(data)#

Parse object from bytes array.

Parameters:

data (bytes) – Object data

Raises:

SPSDKNotImplementedError – If parsing is not implemented

Return type:

Self

store_temp_res(file_name, data, group=None)#

Storing temporary files into workspace.

Parameters:
  • file_name (str) – Name of file to store the data.

  • data (bytes) – Data to store.

  • group (Optional[str]) – Subfolder name, defaults to None

Return type:

None

SBFile - DEVHSM utils#

Utils for DevHSM.

spsdk.sbfile.devhsm.utils.get_devhsm_class(family)#

Get name of DevHsm class based on family.

Parameters:

family (FamilyRevision) – name of the family

Raises:

SPSDKError – If the class is not found

Return type:

Type[Union[DevHsmSB31, DevHsmSBx, DevHsmSBc]]

Returns:

name of the class that supports given family