xref: /openbmc/u-boot/cmd/aes.c (revision 2c79b7a3)
1 /*
2  * Copyright (C) 2014 Marek Vasut <marex@denx.de>
3  *
4  * Command for en/de-crypting block of memory with AES-128-CBC cipher.
5  *
6  * SPDX-License-Identifier:	GPL-2.0+
7  */
8 
9 #include <common.h>
10 #include <command.h>
11 #include <environment.h>
12 #include <aes.h>
13 #include <malloc.h>
14 #include <asm/byteorder.h>
15 #include <linux/compiler.h>
16 
17 DECLARE_GLOBAL_DATA_PTR;
18 
19 /**
20  * do_aes() - Handle the "aes" command-line command
21  * @cmdtp:	Command data struct pointer
22  * @flag:	Command flag
23  * @argc:	Command-line argument count
24  * @argv:	Array of command-line arguments
25  *
26  * Returns zero on success, CMD_RET_USAGE in case of misuse and negative
27  * on error.
28  */
29 static int do_aes(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
30 {
31 	uint32_t key_addr, src_addr, dst_addr, len;
32 	uint8_t *key_ptr, *src_ptr, *dst_ptr;
33 	uint8_t key_exp[AES_EXPAND_KEY_LENGTH];
34 	uint32_t aes_blocks;
35 	int enc;
36 
37 	if (argc != 6)
38 		return CMD_RET_USAGE;
39 
40 	if (!strncmp(argv[1], "enc", 3))
41 		enc = 1;
42 	else if (!strncmp(argv[1], "dec", 3))
43 		enc = 0;
44 	else
45 		return CMD_RET_USAGE;
46 
47 	key_addr = simple_strtoul(argv[2], NULL, 16);
48 	src_addr = simple_strtoul(argv[3], NULL, 16);
49 	dst_addr = simple_strtoul(argv[4], NULL, 16);
50 	len = simple_strtoul(argv[5], NULL, 16);
51 
52 	key_ptr = (uint8_t *)key_addr;
53 	src_ptr = (uint8_t *)src_addr;
54 	dst_ptr = (uint8_t *)dst_addr;
55 
56 	/* First we expand the key. */
57 	aes_expand_key(key_ptr, key_exp);
58 
59 	/* Calculate the number of AES blocks to encrypt. */
60 	aes_blocks = DIV_ROUND_UP(len, AES_KEY_LENGTH);
61 
62 	if (enc)
63 		aes_cbc_encrypt_blocks(key_exp, src_ptr, dst_ptr, aes_blocks);
64 	else
65 		aes_cbc_decrypt_blocks(key_exp, src_ptr, dst_ptr, aes_blocks);
66 
67 	return 0;
68 }
69 
70 /***************************************************/
71 #ifdef CONFIG_SYS_LONGHELP
72 static char aes_help_text[] =
73 	"enc key src dst len - Encrypt block of data $len bytes long\n"
74 	"                          at address $src using a key at address\n"
75 	"                          $key and store the result at address\n"
76 	"                          $dst. The $len size must be multiple of\n"
77 	"                          16 bytes and $key must be 16 bytes long.\n"
78 	"aes dec key src dst len - Decrypt block of data $len bytes long\n"
79 	"                          at address $src using a key at address\n"
80 	"                          $key and store the result at address\n"
81 	"                          $dst. The $len size must be multiple of\n"
82 	"                          16 bytes and $key must be 16 bytes long.";
83 #endif
84 
85 U_BOOT_CMD(
86 	aes, 6, 1, do_aes,
87 	"AES 128 CBC encryption",
88 	aes_help_text
89 );
90