diff --git a/core/cpio_utils.c b/core/cpio_utils.c
index 9faa8019..4802c390 100644
--- a/core/cpio_utils.c
+++ b/core/cpio_utils.c
@@ -706,12 +706,16 @@ int copyfile(struct swupdate_copy *args)
 			ivt = get_aes_ivt();
 
 		if (args->imgaes && strlen(args->imgaes)) {
-				if (!is_hex_str(args->imgaes) || ascii_to_bin(aesbuf, sizeof(aesbuf), args->imgaes)) {
+				size_t imgkeylen = strlen(args->imgaes) / 2;
+
+				if (!is_valid_aes_keylen(imgkeylen) ||
+				    !is_hex_str(args->imgaes) ||
+				    ascii_to_bin(aesbuf, imgkeylen, args->imgaes)) {
 					ERROR("Invalid image aes-key");
 					return -EINVAL;
 				}
 				aes_key = aesbuf;
-				keylen = strlen(args->imgaes) / 2;
+				keylen = imgkeylen;
 		} else {
 			/*
 			 * Only fall back to the default decryption key if the requested cipher matches.
diff --git a/include/util.h b/include/util.h
index 7007d357..4255a126 100644
--- a/include/util.h
+++ b/include/util.h
@@ -34,6 +34,13 @@
 #define AES_192_KEY_LEN	24
 #define AES_256_KEY_LEN	32
 
+static inline bool is_valid_aes_keylen(size_t keylen)
+{
+	return keylen == AES_128_KEY_LEN ||
+	       keylen == AES_192_KEY_LEN ||
+	       keylen == AES_256_KEY_LEN;
+}
+
 #define HWID_REGEXP_PREFIX	"#RE:"
 
 #define BOOTVAR_TRANSACTION "recovery_status"
