diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig index cdb4d29cc..15f541405 100644 --- a/boot/zephyr/Kconfig +++ b/boot/zephyr/Kconfig @@ -724,6 +724,22 @@ config BOOT_ENCRYPT_X25519 help Hidden option selecting x25519 encryption. +if BOOT_ENCRYPT_IMAGE + +choice BOOT_ENCRYPT_ALG + prompt "Algorithm used for image encryption" + default BOOT_ENCRYPT_ALG_AES_128 + +config BOOT_ENCRYPT_ALG_AES_128 + bool "Use AES-128 for image encryption" + +config BOOT_ENCRYPT_ALG_AES_256 + bool "Use AES-256 for image encryption" + +endchoice # BOOT_ENCRYPT_ALG + +endif # BOOT_ENCRYPT_IMAGE + if BOOT_ENCRYPT_X25519 && BOOT_USE_PSA_CRYPTO choice BOOT_HMAC_SHA diff --git a/boot/zephyr/include/mcuboot_config/mcuboot_config.h b/boot/zephyr/include/mcuboot_config/mcuboot_config.h index 8ba030738..e593f9677 100644 --- a/boot/zephyr/include/mcuboot_config/mcuboot_config.h +++ b/boot/zephyr/include/mcuboot_config/mcuboot_config.h @@ -163,6 +163,14 @@ #define MCUBOOT_ENCRYPT_X25519 #endif +#ifdef CONFIG_BOOT_ENCRYPT_ALG_AES_128 +#define MCUBOOT_AES_128 +#endif + +#ifdef CONFIG_BOOT_ENCRYPT_ALG_AES_256 +#define MCUBOOT_AES_256 +#endif + /* Support for HMAC/HKDF using SHA512; this is used in key exchange where * HKDF is used for key expansion and HMAC is used for key verification. */ diff --git a/scripts/imgtool/image.py b/scripts/imgtool/image.py old mode 100644 new mode 100755 index b24e5de8d..112d2ef4e --- a/scripts/imgtool/image.py +++ b/scripts/imgtool/image.py @@ -443,14 +443,23 @@ def ecies_hkdf(self, enckey, plainkey, hmac_sha_alg): else: newpk = X25519PrivateKey.generate() shared = newpk.exchange(enckey._get_public()) + + # Detect AES key length from plainkey size + key_len = len(plainkey) # 16 for AES-128, 32 for AES-256 + + # Generate derived key with appropriate length (key_len + 32 bytes for HMAC) derived_key = HKDF( - algorithm=hmac_sha_alg, length=16 + hmac_sha_alg.digest_size, salt=None, + algorithm=hmac_sha_alg, length=key_len + hmac_sha_alg.digest_size, salt=None, info=b'MCUBoot_ECIES_v1', backend=default_backend()).derive(shared) - encryptor = Cipher(algorithms.AES(derived_key[:16]), + + # Use appropriate key length for AES encryption + encryptor = Cipher(algorithms.AES(derived_key[:key_len]), modes.CTR(bytes([0] * 16)), backend=default_backend()).encryptor() cipherkey = encryptor.update(plainkey) + encryptor.finalize() - mac = hmac.HMAC(derived_key[16:], hmac_sha_alg, + + # Use remaining bytes for HMAC (after the AES key) + mac = hmac.HMAC(derived_key[key_len:], hmac_sha_alg, backend=default_backend()) mac.update(cipherkey) ciphermac = mac.finalize()