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