Raef Coles | 59cf5d8 | 2024-12-09 15:41:13 +0000 | [diff] [blame^] | 1 | #!/usr/bin/env python3 |
| 2 | #------------------------------------------------------------------------------- |
| 3 | # SPDX-FileCopyrightText: Copyright The TrustedFirmware-M Contributors |
| 4 | # |
| 5 | # SPDX-License-Identifier: BSD-3-Clause |
| 6 | # |
| 7 | #------------------------------------------------------------------------------- |
| 8 | |
| 9 | from cryptography.hazmat.primitives.serialization import load_pem_private_key, Encoding, PublicFormat |
| 10 | import logging |
| 11 | logger = logging.getLogger("TF-M") |
| 12 | from os.path import splitext, isfile |
| 13 | |
| 14 | def _load_bin(filepath): |
| 15 | with open(filepath, 'rb') as input_file: |
| 16 | return input_file.read() |
| 17 | |
| 18 | def _load_pem(filepath): |
| 19 | with open(filepath, 'rb') as input_file: |
| 20 | data = input_file.read() |
| 21 | |
| 22 | key = load_pem_private_key(data, password=None) |
| 23 | |
| 24 | # MCUBoot wants DER keys |
| 25 | key_bytes = key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) |
| 26 | logger.info("Loaded DER public key {} of size {} from {}".format(key_bytes, len(key_bytes), filepath)) |
| 27 | |
| 28 | return key_bytes |
| 29 | |
| 30 | def load_bytes_from_file(filepath): |
| 31 | _, extension = splitext(filepath) |
| 32 | |
| 33 | if not filepath or not isfile(filepath): |
| 34 | raise FileNotFoundError |
| 35 | |
| 36 | logging.info("Loading bytes from {} with type {}".format(filepath, extension)) |
| 37 | |
| 38 | if extension == ".pem": |
| 39 | return _load_pem(filepath) |
| 40 | elif extension == ".pub": |
| 41 | return _load_bin(filepath)[4:] |
| 42 | else: |
| 43 | return _load_bin(filepath) |