Loading scripts/imgtool/image.py +19 −4 Changes for scripts/imgtool/image.py: 19 added lines, 4 removed lines. Original line number Diff line number Diff line Loading @@ -26,8 +26,9 @@ from intelhex import IntelHex import hashlib import struct import os.path from .keys import rsa, ecdsa from .keys import rsa, ecdsa, x25519 from cryptography.hazmat.primitives.asymmetric import ec, padding from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat Loading Loading @@ -64,6 +65,7 @@ TLV_VALUES = { 'ENCRSA2048': 0x30, 'ENCKW128': 0x31, 'ENCEC256': 0x32, 'ENCX25519': 0x33, 'DEPENDENCY': 0x40, 'SEC_CNT': 0x50, 'BOOT_RECORD': 0x60, Loading Loading @@ -241,9 +243,13 @@ class Image(): len(self.payload), tsize, self.slot_size) raise click.UsageError(msg) def ecies_p256_hkdf(self, enckey, plainkey): def ecies_hkdf(self, enckey, plainkey): if isinstance(enckey, ecdsa.ECDSA256P1Public): newpk = ec.generate_private_key(ec.SECP256R1(), default_backend()) shared = newpk.exchange(ec.ECDH(), enckey._get_public()) else: newpk = X25519PrivateKey.generate() shared = newpk.exchange(enckey._get_public()) derived_key = HKDF( algorithm=hashes.SHA256(), length=48, salt=None, info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared) Loading @@ -255,9 +261,14 @@ class Image(): backend=default_backend()) mac.update(cipherkey) ciphermac = mac.finalize() if isinstance(enckey, ecdsa.ECDSA256P1Public): pubk = newpk.public_key().public_bytes( encoding=Encoding.X962, format=PublicFormat.UncompressedPoint) else: pubk = newpk.public_key().public_bytes( encoding=Encoding.Raw, format=PublicFormat.Raw) return cipherkey, ciphermac, pubk def create(self, key, public_key_format, enckey, dependencies=None, Loading Loading @@ -392,11 +403,15 @@ class Image(): label=None)) self.enctlv_len = len(cipherkey) tlv.add('ENCRSA2048', cipherkey) elif isinstance(enckey, ecdsa.ECDSA256P1Public): cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey) elif isinstance(enckey, (ecdsa.ECDSA256P1Public, x25519.X25519Public)): cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey) enctlv = pubk + mac + cipherkey self.enctlv_len = len(enctlv) if isinstance(enckey, ecdsa.ECDSA256P1Public): tlv.add('ENCEC256', enctlv) else: tlv.add('ENCX25519', enctlv) nonce = bytes([0] * 16) cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), Loading scripts/imgtool/keys/__init__.py +15 −3 Changes for scripts/imgtool/keys/__init__.py: 15 added lines, 3 removed lines. Original line number Diff line number Diff line Loading @@ -18,19 +18,27 @@ Cryptographic key management for imgtool. from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey, EllipticCurvePublicKey from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey from cryptography.hazmat.primitives.asymmetric.rsa import ( RSAPrivateKey, RSAPublicKey) from cryptography.hazmat.primitives.asymmetric.ec import ( EllipticCurvePrivateKey, EllipticCurvePublicKey) from cryptography.hazmat.primitives.asymmetric.ed25519 import ( Ed25519PrivateKey, Ed25519PublicKey) from cryptography.hazmat.primitives.asymmetric.x25519 import ( X25519PrivateKey, X25519PublicKey) from .rsa import RSA, RSAPublic, RSAUsageError, RSA_KEY_SIZES from .ecdsa import ECDSA256P1, ECDSA256P1Public, ECDSAUsageError from .ed25519 import Ed25519, Ed25519Public, Ed25519UsageError from .x25519 import X25519, X25519Public, X25519UsageError class PasswordRequired(Exception): """Raised to indicate that the key is password protected, but a password was not specified.""" pass def load(path, passwd=None): """Try loading a key from the given path. Returns None if the password wasn't specified.""" with open(path, 'rb') as f: Loading Loading @@ -78,5 +86,9 @@ def load(path, passwd=None): return Ed25519(pk) elif isinstance(pk, Ed25519PublicKey): return Ed25519Public(pk) elif isinstance(pk, X25519PrivateKey): return X25519(pk) elif isinstance(pk, X25519PublicKey): return X25519Public(pk) else: raise Exception("Unknown key type: " + str(type(pk))) scripts/imgtool/keys/x25519.py 0 → 100644 +105 −0 Changes for scripts/imgtool/keys/x25519.py: 105 added lines, 0 removed lines. Original line number Diff line number Diff line """ X25519 key management """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import x25519 from .general import KeyClass class X25519UsageError(Exception): pass class X25519Public(KeyClass): def __init__(self, key): self.key = key def shortname(self): return "x25519" def _unsupported(self, name): raise X25519UsageError("Operation {} requires private key".format(name)) def _get_public(self): return self.key def get_public_bytes(self): # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format return self._get_public().public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo) def get_private_bytes(self, minimal): self._unsupported('get_private_bytes') def export_private(self, path, passwd=None): self._unsupported('export_private') def export_public(self, path): """Write the public key to the given file.""" pem = self._get_public().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) with open(path, 'wb') as f: f.write(pem) def sig_type(self): return "X25519" def sig_tlv(self): return "X25519" def sig_len(self): return 32 class X25519(X25519Public): """ Wrapper around an X25519 private key. """ def __init__(self, key): """key should be an instance of EllipticCurvePrivateKey""" self.key = key @staticmethod def generate(): pk = x25519.X25519PrivateKey.generate() return X25519(pk) def _get_public(self): return self.key.public_key() def get_private_bytes(self, minimal): raise X25519UsageError("Operation not supported with {} keys".format( self.shortname())) def export_private(self, path, passwd=None): """ Write the private key to the given file, protecting it with the optional password. """ if passwd is None: enc = serialization.NoEncryption() else: enc = serialization.BestAvailableEncryption(passwd) pem = self.key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=enc) with open(path, 'wb') as f: f.write(pem) def sign_digest(self, digest): """Return the actual signature""" return self.key.sign(data=digest) def verify_digest(self, signature, digest): """Verify that signature is valid for given digest""" k = self.key if isinstance(self.key, x25519.X25519PrivateKey): k = self.key.public_key() return k.verify(signature=signature, data=digest) Loading
scripts/imgtool/image.py +19 −4 Changes for scripts/imgtool/image.py: 19 added lines, 4 removed lines. Original line number Diff line number Diff line Loading @@ -26,8 +26,9 @@ from intelhex import IntelHex import hashlib import struct import os.path from .keys import rsa, ecdsa from .keys import rsa, ecdsa, x25519 from cryptography.hazmat.primitives.asymmetric import ec, padding from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat Loading Loading @@ -64,6 +65,7 @@ TLV_VALUES = { 'ENCRSA2048': 0x30, 'ENCKW128': 0x31, 'ENCEC256': 0x32, 'ENCX25519': 0x33, 'DEPENDENCY': 0x40, 'SEC_CNT': 0x50, 'BOOT_RECORD': 0x60, Loading Loading @@ -241,9 +243,13 @@ class Image(): len(self.payload), tsize, self.slot_size) raise click.UsageError(msg) def ecies_p256_hkdf(self, enckey, plainkey): def ecies_hkdf(self, enckey, plainkey): if isinstance(enckey, ecdsa.ECDSA256P1Public): newpk = ec.generate_private_key(ec.SECP256R1(), default_backend()) shared = newpk.exchange(ec.ECDH(), enckey._get_public()) else: newpk = X25519PrivateKey.generate() shared = newpk.exchange(enckey._get_public()) derived_key = HKDF( algorithm=hashes.SHA256(), length=48, salt=None, info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared) Loading @@ -255,9 +261,14 @@ class Image(): backend=default_backend()) mac.update(cipherkey) ciphermac = mac.finalize() if isinstance(enckey, ecdsa.ECDSA256P1Public): pubk = newpk.public_key().public_bytes( encoding=Encoding.X962, format=PublicFormat.UncompressedPoint) else: pubk = newpk.public_key().public_bytes( encoding=Encoding.Raw, format=PublicFormat.Raw) return cipherkey, ciphermac, pubk def create(self, key, public_key_format, enckey, dependencies=None, Loading Loading @@ -392,11 +403,15 @@ class Image(): label=None)) self.enctlv_len = len(cipherkey) tlv.add('ENCRSA2048', cipherkey) elif isinstance(enckey, ecdsa.ECDSA256P1Public): cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey) elif isinstance(enckey, (ecdsa.ECDSA256P1Public, x25519.X25519Public)): cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey) enctlv = pubk + mac + cipherkey self.enctlv_len = len(enctlv) if isinstance(enckey, ecdsa.ECDSA256P1Public): tlv.add('ENCEC256', enctlv) else: tlv.add('ENCX25519', enctlv) nonce = bytes([0] * 16) cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), Loading
scripts/imgtool/keys/__init__.py +15 −3 Changes for scripts/imgtool/keys/__init__.py: 15 added lines, 3 removed lines. Original line number Diff line number Diff line Loading @@ -18,19 +18,27 @@ Cryptographic key management for imgtool. from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePrivateKey, EllipticCurvePublicKey from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey from cryptography.hazmat.primitives.asymmetric.rsa import ( RSAPrivateKey, RSAPublicKey) from cryptography.hazmat.primitives.asymmetric.ec import ( EllipticCurvePrivateKey, EllipticCurvePublicKey) from cryptography.hazmat.primitives.asymmetric.ed25519 import ( Ed25519PrivateKey, Ed25519PublicKey) from cryptography.hazmat.primitives.asymmetric.x25519 import ( X25519PrivateKey, X25519PublicKey) from .rsa import RSA, RSAPublic, RSAUsageError, RSA_KEY_SIZES from .ecdsa import ECDSA256P1, ECDSA256P1Public, ECDSAUsageError from .ed25519 import Ed25519, Ed25519Public, Ed25519UsageError from .x25519 import X25519, X25519Public, X25519UsageError class PasswordRequired(Exception): """Raised to indicate that the key is password protected, but a password was not specified.""" pass def load(path, passwd=None): """Try loading a key from the given path. Returns None if the password wasn't specified.""" with open(path, 'rb') as f: Loading Loading @@ -78,5 +86,9 @@ def load(path, passwd=None): return Ed25519(pk) elif isinstance(pk, Ed25519PublicKey): return Ed25519Public(pk) elif isinstance(pk, X25519PrivateKey): return X25519(pk) elif isinstance(pk, X25519PublicKey): return X25519Public(pk) else: raise Exception("Unknown key type: " + str(type(pk)))
scripts/imgtool/keys/x25519.py 0 → 100644 +105 −0 Changes for scripts/imgtool/keys/x25519.py: 105 added lines, 0 removed lines. Original line number Diff line number Diff line """ X25519 key management """ from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import x25519 from .general import KeyClass class X25519UsageError(Exception): pass class X25519Public(KeyClass): def __init__(self, key): self.key = key def shortname(self): return "x25519" def _unsupported(self, name): raise X25519UsageError("Operation {} requires private key".format(name)) def _get_public(self): return self.key def get_public_bytes(self): # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format return self._get_public().public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo) def get_private_bytes(self, minimal): self._unsupported('get_private_bytes') def export_private(self, path, passwd=None): self._unsupported('export_private') def export_public(self, path): """Write the public key to the given file.""" pem = self._get_public().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) with open(path, 'wb') as f: f.write(pem) def sig_type(self): return "X25519" def sig_tlv(self): return "X25519" def sig_len(self): return 32 class X25519(X25519Public): """ Wrapper around an X25519 private key. """ def __init__(self, key): """key should be an instance of EllipticCurvePrivateKey""" self.key = key @staticmethod def generate(): pk = x25519.X25519PrivateKey.generate() return X25519(pk) def _get_public(self): return self.key.public_key() def get_private_bytes(self, minimal): raise X25519UsageError("Operation not supported with {} keys".format( self.shortname())) def export_private(self, path, passwd=None): """ Write the private key to the given file, protecting it with the optional password. """ if passwd is None: enc = serialization.NoEncryption() else: enc = serialization.BestAvailableEncryption(passwd) pem = self.key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=enc) with open(path, 'wb') as f: f.write(pem) def sign_digest(self, digest): """Return the actual signature""" return self.key.sign(data=digest) def verify_digest(self, signature, digest): """Verify that signature is valid for given digest""" k = self.key if isinstance(self.key, x25519.X25519PrivateKey): k = self.key.public_key() return k.verify(signature=signature, data=digest)