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