1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (C) 2014 Marek Vasut <marex@denx.de>
5 * Command for en/de-crypting block of memory with AES-[128/192/256]-CBC cipher.
10 #include <uboot_aes.h>
12 #include <asm/byteorder.h>
13 #include <linux/compiler.h>
16 u32 aes_get_key_len(char *command)
18 u32 key_len = AES128_KEY_LENGTH;
20 if (!strcmp(command, "aes.192"))
21 key_len = AES192_KEY_LENGTH;
22 else if (!strcmp(command, "aes.256"))
23 key_len = AES256_KEY_LENGTH;
29 * do_aes() - Handle the "aes" command-line command
30 * @cmdtp: Command data struct pointer
32 * @argc: Command-line argument count
33 * @argv: Array of command-line arguments
35 * Returns zero on success, CMD_RET_USAGE in case of misuse and negative
38 static int do_aes(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[])
40 uint32_t key_addr, iv_addr, src_addr, dst_addr, len;
41 uint8_t *key_ptr, *iv_ptr, *src_ptr, *dst_ptr;
42 u8 key_exp[AES256_EXPAND_KEY_LENGTH];
43 u32 aes_blocks, key_len;
49 key_len = aes_get_key_len(argv[0]);
51 if (!strncmp(argv[1], "enc", 3))
53 else if (!strncmp(argv[1], "dec", 3))
58 key_addr = simple_strtoul(argv[2], NULL, 16);
59 iv_addr = simple_strtoul(argv[3], NULL, 16);
60 src_addr = simple_strtoul(argv[4], NULL, 16);
61 dst_addr = simple_strtoul(argv[5], NULL, 16);
62 len = simple_strtoul(argv[6], NULL, 16);
64 key_ptr = (uint8_t *)map_sysmem(key_addr, key_len);
65 iv_ptr = (uint8_t *)map_sysmem(iv_addr, 128 / 8);
66 src_ptr = (uint8_t *)map_sysmem(src_addr, len);
67 dst_ptr = (uint8_t *)map_sysmem(dst_addr, len);
69 /* First we expand the key. */
70 aes_expand_key(key_ptr, key_len, key_exp);
72 /* Calculate the number of AES blocks to encrypt. */
73 aes_blocks = DIV_ROUND_UP(len, AES_BLOCK_LENGTH);
76 aes_cbc_encrypt_blocks(key_len, key_exp, iv_ptr, src_ptr,
79 aes_cbc_decrypt_blocks(key_len, key_exp, iv_ptr, src_ptr,
82 unmap_sysmem(key_ptr);
84 unmap_sysmem(src_ptr);
85 unmap_sysmem(dst_ptr);
90 /***************************************************/
91 #ifdef CONFIG_SYS_LONGHELP
92 static char aes_help_text[] =
93 "[.128,.192,.256] enc key iv src dst len - Encrypt block of data $len bytes long\n"
94 " at address $src using a key at address\n"
95 " $key with initialization vector at address\n"
96 " $iv. Store the result at address $dst.\n"
97 " The $len size must be multiple of 16 bytes.\n"
98 " The $key and $iv must be 16 bytes long.\n"
99 "aes [.128,.192,.256] dec key iv src dst len - Decrypt block of data $len bytes long\n"
100 " at address $src using a key at address\n"
101 " $key with initialization vector at address\n"
102 " $iv. Store the result at address $dst.\n"
103 " The $len size must be multiple of 16 bytes.\n"
104 " The $key and $iv must be 16 bytes long.";
109 "AES 128/192/256 CBC encryption",