Keys#
Nxpcrypto, a component of SPSDK (Secure Provisioning SDK), offers a suite of utilities for cryptographic operations. This Jupyter notebook guides you through the process of generating cryptographic keys using nxpcrypto.
Cryptographic keys are fundamental to secure communication and data protection. They come in two main types:
Symmetric keys: Used in algorithms where the same key is used for both encryption and decryption.
Asymmetric keys: Consist of a key pair - a public key for encryption and a private key for decryption.
In this guide, we’ll concentrate on generating asymmetric key pairs. The examples cover classic RSA and Elliptic Curve Cryptography (ECC) keys as well as post-quantum keys (ML-DSA and LMS). ECC is a modern approach to public-key cryptography based on the algebraic structure of elliptic curves over finite fields. It offers smaller key sizes and faster computations compared to RSA while maintaining equivalent security levels. Post-quantum algorithms are designed to stay secure even against attacks using quantum computers.
Key management best practices:#
Generate unique keys for each project or application.
Store keys securely, preferably in a hardware security module (HSM) or a secure key management system.
Protect private keys with strong passwords or encryption.
Implement access controls to limit who can use or manage the keys.
Remember, the security of your entire system often depends on the security of your cryptographic keys. Treat them with utmost care and follow industry best practices for key management.
Supported Key types#
The value in the brackets is the key type name used by the -k/--key-type option of the nxpcrypto key generate command.
RSA
2048-bit (
rsa2048)3072-bit (
rsa3072)4096-bit (
rsa4096)
ECC
NIST P-256 (
secp256r1)NIST P-384 (
secp384r1)NIST P-521 (
secp521r1)
Chinese national cryptography standards (requires spsdk[oscca])
SM2 (
sm2)
Post Quantum
ML-DSA (FIPS 204): ML-DSA-44 (
mldsa44), ML-DSA-65 (mldsa65), ML-DSA-87 (mldsa87)Dilithium (pre-standard version of ML-DSA, requires
spsdk[pqc]): Dilithium2 (dil2), Dilithium3 (dil3), Dilithium5 (dil5)LMS - Leighton-Micali hash-based signatures (requires
spsdk[pqc]):lms, the LMS parameters must be specified using the--lms-hash-size,--lms-tree-heightand--lms-winternitzoptions
The list of key types available in your installation is printed by nxpcrypto key generate --help.
Now, let’s proceed with generating keys using nxpcrypto in our Jupyter notebook.
1. Prerequisites#
SPSDK is needed with examples extension.
pip install spsdk[examples](Please refer to the installation documentation.)SM2 keys need the OSCCA extension
pip install spsdk[oscca], Dilithium and LMS keys need the PQC extensionpip install spsdk[pqc].
Let’s prepare also workspace and variables.
# Initialization cell
import os
# This env variable sets colored logger output to STDOUT
%env JUPYTER_SPSDK=1
# Set a magic for command execution and echo
%alias execute echo %l && %l
%alias_magic ! execute
env: JUPYTER_SPSDK=1
Created `%!` as an alias for `%execute`.
WORKSPACE = "workspace/" # change this to path to your workspace
VERBOSITY = (
"-v" # verbosity of commands, might be -v or -vv for debug or blank for no additional info
)
# prepare the workspace directory
os.makedirs(WORKSPACE, exist_ok=True)
2. Keys Generation#
This section is used for key generation. Each time the keys generate command is called, an asymmetric key pair is generated. Key pair includes a public key (.pub) and a corresponding private key (.pem).
Besides the key type, the nxpcrypto key generate command accepts these options:
-o/--output: path to the private key file, the public key is stored next to it with the.pubextension-e/--encoding: encoding of the key files,pem(default),derornxp-p/--password: password used to encrypt the private key file--force: overwrite existing files
2.1 Generate Keys with nxpcrypto CLI#
The nxpcrypto application provides command line interface which can be used for key generation as well as for verification generated key pair.
KEY_TYPE = "secp256r1"
ROTK_PRIVATE_KEY_PATH = WORKSPACE + f"srk0_{KEY_TYPE}.pem"
ROTK_PUBLIC_KEY_PATH = WORKSPACE + f"srk0_{KEY_TYPE}.pub"
%! nxpcrypto $VERBOSITY key generate -k $KEY_TYPE -o $ROTK_PRIVATE_KEY_PATH --force
# verify that keys were generated
assert os.path.exists(ROTK_PRIVATE_KEY_PATH)
assert os.path.exists(ROTK_PUBLIC_KEY_PATH)
# check that the keys match
%! nxpcrypto $VERBOSITY key verify -k1 $ROTK_PRIVATE_KEY_PATH -k2 $ROTK_PUBLIC_KEY_PATH
nxpcrypto -v key generate -k secp256r1 -o workspace/srk0_secp256r1.pem --force
The key pair has been created: workspace/srk0_secp256r1.pub, workspace/srk0_secp256r1.pem
nxpcrypto -v key verify -k1 workspace/srk0_secp256r1.pem -k2 workspace/srk0_secp256r1.pub
Keys match.
Post-quantum keys#
ML-DSA keys are generated in the same way, just by selecting the corresponding key type.
KEY_TYPE = "mldsa87"
MLDSA_PRIVATE_KEY_PATH = WORKSPACE + f"key_{KEY_TYPE}.pem"
MLDSA_PUBLIC_KEY_PATH = WORKSPACE + f"key_{KEY_TYPE}.pub"
%! nxpcrypto $VERBOSITY key generate -k $KEY_TYPE -o $MLDSA_PRIVATE_KEY_PATH --force
# verify that keys were generated
assert os.path.exists(MLDSA_PRIVATE_KEY_PATH)
assert os.path.exists(MLDSA_PUBLIC_KEY_PATH)
# check that the keys match
%! nxpcrypto $VERBOSITY key verify -k1 $MLDSA_PRIVATE_KEY_PATH -k2 $MLDSA_PUBLIC_KEY_PATH
nxpcrypto -v key generate -k mldsa87 -o workspace/key_mldsa87.pem --force
The key pair has been created: workspace/key_mldsa87.pub, workspace/key_mldsa87.pem
nxpcrypto -v key verify -k1 workspace/key_mldsa87.pem -k2 workspace/key_mldsa87.pub
Keys match.
LMS key generation needs the LMS parameters: the hash size (32 or 24 bytes), the height of the Merkle tree (defines number of possible signatures 2^height) and the Winternitz parameter.
Note: LMS is a stateful signature scheme, every signature consumes one one-time key. SPSDK does not update the signature counter in the private key file, so storing LMS private keys in a local file is strongly discouraged for production use. Use an HSM instead.
from spsdk.crypto.lms import IS_LMS_SUPPORTED
LMS_PRIVATE_KEY_PATH = WORKSPACE + "key_lms.pem"
LMS_PUBLIC_KEY_PATH = WORKSPACE + "key_lms.pub"
# LMS keys are available only with the PQC extension installed: pip install spsdk[pqc]
if IS_LMS_SUPPORTED:
%! nxpcrypto $VERBOSITY key generate -k lms --lms-hash-size 32 --lms-tree-height 5 --lms-winternitz 8 -o $LMS_PRIVATE_KEY_PATH --force
# verify that keys were generated
assert os.path.exists(LMS_PRIVATE_KEY_PATH)
assert os.path.exists(LMS_PUBLIC_KEY_PATH)
else:
print("LMS keys are not supported, install the PQC extension: pip install spsdk[pqc]")
nxpcrypto -v key generate -k lms --lms-hash-size 32 --lms-tree-height 5 --lms-winternitz 8 -o workspace/key_lms.pem --force
The key pair has been created: workspace/key_lms.pub, workspace/key_lms.pem
2.2 Convert Keys with nxpcrypto CLI#
The nxpcrypto key convert command converts a key into a different encoding (pem, der or raw). With the -p/--puk flag the public key is extracted from the private key.
ROTK_PUBLIC_KEY_DER_PATH = WORKSPACE + "srk0_secp256r1_pub.der"
%! nxpcrypto $VERBOSITY key convert -e der -i $ROTK_PRIVATE_KEY_PATH -p -o $ROTK_PUBLIC_KEY_DER_PATH
# check that the extracted public key matches the original one
%! nxpcrypto $VERBOSITY key verify -k1 $ROTK_PUBLIC_KEY_DER_PATH -k2 $ROTK_PUBLIC_KEY_PATH
nxpcrypto -v key convert -e der -i workspace/srk0_secp256r1.pem -p -o workspace/srk0_secp256r1_pub.der
nxpcrypto -v key verify -k1 workspace/srk0_secp256r1_pub.der -k2 workspace/srk0_secp256r1.pub
Keys match.
2.3 Generating Keys with nxpcrypto API#
The spsdk.crypto.keys module handles key operations in the SPSDK. It provides two base classes, PrivateKey and PublicKey, which serve as the foundation for working with various types of keys. SPSDK supports RSA, ECC, SM2 and post-quantum (ML-DSA, Dilithium and LMS) keys with PEM and DER formats. In addition to PEM and DER encoding, SPSDK defines NXP encoding that is used with the NXP devices that are memory constrained.
Private Key
The PrivateKey class is a fundamental component of the SPSDK, acting as an abstract base class for private keys. It inherits from the BaseClass and includes abstract methods that must be implemented by any subclasses.
Public Key
Similarly, the PublicKey class is a crucial part of the SPSDK, functioning as an abstract base class for public keys. Like the PrivateKey class, it extends the BaseClass and defines abstract methods that its subclasses must implement.
from spsdk.crypto.keys import EccCurve, PrivateKeyEcc, PrivateKeyMLDSA, PrivateKeyRsa
# Let's start with RSA key pair
RSA_PRIVATE_KEY_PATH = WORKSPACE + "rsa_2048.pem"
RSA_PUBLIC_KEY_PATH = WORKSPACE + "rsa_2048.pub"
priv_key_2048 = PrivateKeyRsa.generate_key(key_size=2048)
pub_key_2048 = priv_key_2048.get_public_key()
# Generate and save rsa keys (size 2048) - pem format
priv_key_2048.save(RSA_PRIVATE_KEY_PATH)
pub_key_2048.save(RSA_PUBLIC_KEY_PATH)
# verify that keys were generated
assert os.path.exists(RSA_PRIVATE_KEY_PATH)
assert os.path.exists(RSA_PUBLIC_KEY_PATH)
match = priv_key_2048.verify_public_key(pub_key_2048)
assert match, "Private key does not match the public key"
print(f"The RSA key pair was generated {RSA_PRIVATE_KEY_PATH}, {RSA_PUBLIC_KEY_PATH}.")
The RSA key pair was generated workspace/rsa_2048.pem, workspace/rsa_2048.pub.
# Now, let's generate ECC key pair
ECC_PRIVATE_KEY_PATH = WORKSPACE + "ecc_p256.pem"
ECC_PUBLIC_KEY_PATH = WORKSPACE + "ecc_p256.pub"
priv_key_p256 = PrivateKeyEcc.generate_key(curve_name=EccCurve.SECP256R1)
pub_key_p256 = priv_key_p256.get_public_key()
priv_key_p256.save(ECC_PRIVATE_KEY_PATH)
pub_key_p256.save(ECC_PUBLIC_KEY_PATH)
# verify that keys were generated
assert os.path.exists(ECC_PRIVATE_KEY_PATH)
assert os.path.exists(ECC_PUBLIC_KEY_PATH)
match = priv_key_p256.verify_public_key(pub_key_p256)
assert match, "Private key does not match the public key"
print(f"The ECC key pair was generated {ECC_PRIVATE_KEY_PATH}, {ECC_PUBLIC_KEY_PATH}.")
The ECC key pair was generated workspace/ecc_p256.pem, workspace/ecc_p256.pub.
# Generate ML-DSA key pair, the level is the NIST security level (2: ML-DSA-44, 3: ML-DSA-65, 5: ML-DSA-87)
MLDSA_API_PRIVATE_KEY_PATH = WORKSPACE + "mldsa_87.pem"
MLDSA_API_PUBLIC_KEY_PATH = WORKSPACE + "mldsa_87.pub"
priv_key_mldsa = PrivateKeyMLDSA.generate_key(level=5)
pub_key_mldsa = priv_key_mldsa.get_public_key()
priv_key_mldsa.save(MLDSA_API_PRIVATE_KEY_PATH)
pub_key_mldsa.save(MLDSA_API_PUBLIC_KEY_PATH)
# verify that keys were generated
assert os.path.exists(MLDSA_API_PRIVATE_KEY_PATH)
assert os.path.exists(MLDSA_API_PUBLIC_KEY_PATH)
match = priv_key_mldsa.verify_public_key(pub_key_mldsa)
assert match, "Private key does not match the public key"
print(
f"The ML-DSA key pair was generated {MLDSA_API_PRIVATE_KEY_PATH}, {MLDSA_API_PUBLIC_KEY_PATH}."
)
# sign data and verify the signature
signature = priv_key_mldsa.sign(b"Hello SPSDK")
assert pub_key_mldsa.verify_signature(signature, b"Hello SPSDK")
print(f"Signature of {len(signature)} bytes was verified.")
The ML-DSA key pair was generated workspace/mldsa_87.pem, workspace/mldsa_87.pub.
Signature of 4627 bytes was verified.
The get_supported_keys_generators function returns all key types supported by the current installation together with the generator function and its parameters. It is used by the nxpcrypto key generate command and it can be used to generate any supported key type in a generic way.
from spsdk.crypto.keys import get_supported_keys_generators
generators = get_supported_keys_generators()
print(f"Supported key types: {', '.join(generators)}")
# generate a key pair by the key type name
generator, params = generators["secp384r1"]
priv_key = generator(**params)
pub_key = priv_key.get_public_key()
assert priv_key.verify_public_key(pub_key)
print(f"Generated {priv_key.__class__.__name__} with key size {priv_key.key_size} bits.")
Supported key types: rsa2048, rsa3072, rsa4096, secp256r1, secp384r1, secp521r1, sm2, dil2, dil3, dil5, mldsa44, mldsa65, mldsa87, lms
Generated PrivateKeyEcc with key size 384 bits.