aes.c 2.5 KB

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