#!/usr/bin/env python3 # PYTHON_ARGCOMPLETE_OK import logging import argparse from struct import unpack from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto.Signature import pkcs1_15 try: import argcomplete except ImportError: argcomplete = None from fiptool import FIP, IMAGE_ALIGN, init_logging ENCRYPTION_KEY_SIZE = 16 ENCRYPTION_BLOCK_SIZE = 16 IV_ZERO = b"\0" * ENCRYPTION_BLOCK_SIZE class SignedFIP(FIP): def __init__(self, root_priv_path, bl_priv_path): super().__init__() with open(root_priv_path, "rb") as fp: din = fp.read() self.root_priv = RSA.import_key(din) with open(bl_priv_path, "rb") as fp: din = fp.read() self.bl_priv = RSA.import_key(din) def read_fip(self, path): super().read_fip(path) # Verity the reading of fip.bin with open(path, "rb") as fp: assert fp.read() == self.make() def rsa_to_n(self, rsa): return rsa.n.to_bytes(rsa.size_in_bytes(), byteorder="big") def print_kpub_hash(self, bytes): bytes_str = ['{:02x}'.format(int(i)) for i in bytes] logging.info("KPUB_HASH:" + "".join(bytes_str)) def sign_bl_pk(self): self.param1["ROOT_PK"].content = self.rsa_to_n(self.root_priv) kpub_hash = SHA256.new(self.param1["ROOT_PK"].content[:256]) self.print_kpub_hash(kpub_hash.digest()) self.param1["BL_PK"].content = self.rsa_to_n(self.bl_priv) digest = SHA256.new(self.rsa_to_n(self.bl_priv)) sig = pkcs1_15.new(self.root_priv).sign(digest) self.param1["BL_PK_SIG"].content = sig def sign_by_bl_priv(self, image): digest = SHA256.new(image) return pkcs1_15.new(self.bl_priv).sign(digest) def sign(self): logging.info("sign fip.bin") self.param1["FIP_FLAGS"].content = self.FIP_FLAGS_SCS_MASK | self.param1["FIP_FLAGS"].toint() self.sign_bl_pk() cc = self.param1["CHIP_CONF"].content cc_size = unpack("