blob: 249c93f1b3226597e5d813769472e1605f0f72cf [file] [log] [blame]
Raef Coles59cf5d82024-12-09 15:41:13 +00001#-------------------------------------------------------------------------------
2# SPDX-FileCopyrightText: Copyright The TrustedFirmware-M Contributors
3#
4# SPDX-License-Identifier: BSD-3-Clause
5#
6#-------------------------------------------------------------------------------
7
8from cryptography.hazmat.primitives.serialization import load_pem_private_key, Encoding, PublicFormat
9import logging
10logger = logging.getLogger("TF-M")
11from os.path import splitext, isfile
12
13def _load_bin(filepath):
14 with open(filepath, 'rb') as input_file:
15 return input_file.read()
16
17def _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
29def 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)