def getTrailer(signature, sigTypeDescrip, descripFixedSize, sigFixedSize): """ create a trailer which has the following format [a + b + c], where a = signature type description (Use fixed size to store it. Use zero to fill up the rest if description size is smaller than fixed size) b = size of signature (converted into hexadecimal representation in 32 bits in little endian format) c = signature (Used fixed size to store it. Use zero to fill up the rest if signature size is smaller than fixed size) :param signature: :param sigTypeDescrip: signature type description :param descripFixedSize: fixed size in bytes for storing signature type description :param sigFixedSize: fixed size in bytes for storing signature :return: """ trailer = bytearray() # append signature type description to fixed sigTypeDescrip = bytearray(source=sigTypeDescrip, encoding="utf-8") typeDescripSize = len(sigTypeDescrip) if typeDescripSize > descripFixedSize: raise Exception( "Signature type description exceeded allowed size! Description size: " + sigTypeDescrip + ". Allowed maximum size: " + descripFixedSize + ". Description given: " + sigTypeDescrip) padSize = descripFixedSize - typeDescripSize pad = bytearray(padSize) trailer.extend(sigTypeDescrip) trailer.extend(pad) # append signature size as a 4-byte filed in little endian format sigSize = len(signature) sigSizeFiled = hex(sigSize) sigSizeFiled = format32BitHexStr(sigSizeFiled) sigSizeFiled = toLitteEndianByte(sigSizeFiled) trailer.extend(sigSizeFiled) # append signature if len(signature) > sigFixedSize: raise Exception( "Signature size exceeded allowed size! signature size: " + sigSize + ". Allowed maximum size: " + sigFixedSize) padSize = sigFixedSize - sigSize pad = bytearray(padSize) trailer.extend(signature) trailer.extend(pad) return trailer
def addOTADescriptorToImage(inputImagePath, otaDescriptor, outputImagePath): """ Add given OTA descriptor into given image :param inputImagePath: :param otaDescriptor: :param outputImagePath: :return: """ with open(inputImagePath, "rb") as fIn: data = fIn.read() with open(outputImagePath, "wb") as fOut: # 1. Add sequence number sequenceField = toLitteEndianByte(otaDescriptor.sequenceNumber) fOut.write(sequenceField) # 2. Add start address startAddrField = toLitteEndianByte(otaDescriptor.startAddress) fOut.write(startAddrField) # 3. Add end address endAddrField = toLitteEndianByte(otaDescriptor.endAddress) fOut.write(endAddrField) # 4. Add execution address execAddrField = toLitteEndianByte(otaDescriptor.executionAddress) fOut.write(execAddrField) # 5. Add hardware ID HardwareIdField = toLitteEndianByte(otaDescriptor.hardwareID) fOut.write(HardwareIdField) # 6. Add reserved bytes reserveField = toLitteEndianByte(otaDescriptor.reserves) fOut.write(reserveField) fOut.write(data)