Skip to content

Commit

Permalink
scripts: ncs-provision: Allow to upload keys to KMU from public key file
Browse files Browse the repository at this point in the history
User should be able to upload public key to KMU using private
or public PEM file.

Signed-off-by: Lukasz Fundakowski <[email protected]>
  • Loading branch information
fundakol committed Feb 28, 2025
1 parent 4dfdc18 commit 66f7d8a
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions scripts/west_commands/ncs_provision.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
from typing import Any

import yaml
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives.serialization import (
load_pem_private_key,
load_pem_public_key,
)
from west.commands import WestCommand

KEY_SLOTS: dict[str, list[int]] = {
Expand Down Expand Up @@ -119,7 +122,7 @@ def do_add_parser(self, parser_adder):
epilog=textwrap.dedent("""
Example input YAML file:
- keyname: UROT_PUBKEY
keys: ["private-key1.pem", "private-key2.pem"]
keys: ["key1.pem", "key2.pem"]
policy: lock
"""),
formatter_class=argparse.RawDescriptionHelpFormatter
Expand All @@ -132,7 +135,7 @@ def do_add_parser(self, parser_adder):
type=Path,
action="append",
dest="keys",
help="Input .pem file with ED25519 private key",
help="Input .pem file with ED25519 private or public key",
)
upload_parser.add_argument(
"--keyname",
Expand Down Expand Up @@ -239,9 +242,13 @@ def _generate_slots(self, keyname: str, keys: str, policy: str) -> list[SlotPara
def _get_public_key_hex(keyfile: str) -> str:
"""Return the public key hex from the given keyfile."""
with open(keyfile, "rb") as f:
priv_key = load_pem_private_key(f.read(), password=None)
pub_key = priv_key.public_key()
pub_key_hex = f"0x{pub_key.public_bytes_raw().hex()}"
try:
public_key = load_pem_public_key(f.read())
except ValueError:
# it seems it is not public key, so lets try with private
private_key = load_pem_private_key(f.read(), password=None)
public_key = private_key.public_key()
pub_key_hex = f"0x{public_key.public_bytes_raw().hex()}"
return pub_key_hex

@staticmethod
Expand Down

0 comments on commit 66f7d8a

Please sign in to comment.