Skip to content

Commit 4c74eb7

Browse files
committed
scripts: ncs-provision: Allow to upload keys to KMU from public key file
User should be able to upload public key to KMU using private or public PEM file. Signed-off-by: Lukasz Fundakowski <lukasz.fundakowski@nordicsemi.no>
1 parent 4dfdc18 commit 4c74eb7

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

scripts/west_commands/ncs_provision.py

+14-6
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@
1414
from typing import Any
1515

1616
import yaml
17-
from cryptography.hazmat.primitives.serialization import load_pem_private_key
17+
from cryptography.hazmat.primitives.serialization import (
18+
load_pem_private_key,
19+
load_pem_public_key,
20+
)
1821
from west.commands import WestCommand
1922

2023
KEY_SLOTS: dict[str, list[int]] = {
@@ -119,7 +122,7 @@ def do_add_parser(self, parser_adder):
119122
epilog=textwrap.dedent("""
120123
Example input YAML file:
121124
- keyname: UROT_PUBKEY
122-
keys: ["private-key1.pem", "private-key2.pem"]
125+
keys: ["key1.pem", "key2.pem"]
123126
policy: lock
124127
"""),
125128
formatter_class=argparse.RawDescriptionHelpFormatter
@@ -132,7 +135,7 @@ def do_add_parser(self, parser_adder):
132135
type=Path,
133136
action="append",
134137
dest="keys",
135-
help="Input .pem file with ED25519 private key",
138+
help="Input .pem file with ED25519 private or public key",
136139
)
137140
upload_parser.add_argument(
138141
"--keyname",
@@ -239,9 +242,14 @@ def _generate_slots(self, keyname: str, keys: str, policy: str) -> list[SlotPara
239242
def _get_public_key_hex(keyfile: str) -> str:
240243
"""Return the public key hex from the given keyfile."""
241244
with open(keyfile, "rb") as f:
242-
priv_key = load_pem_private_key(f.read(), password=None)
243-
pub_key = priv_key.public_key()
244-
pub_key_hex = f"0x{pub_key.public_bytes_raw().hex()}"
245+
data = f.read()
246+
try:
247+
public_key = load_pem_public_key(data)
248+
except ValueError:
249+
# it seems it is not public key, so lets try with private
250+
private_key = load_pem_private_key(data, password=None)
251+
public_key = private_key.public_key()
252+
pub_key_hex = f"0x{public_key.public_bytes_raw().hex()}"
245253
return pub_key_hex
246254

247255
@staticmethod

0 commit comments

Comments
 (0)