test_aes_perf.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Unlicense OR CC0-1.0
  5. */
  6. /* mbedTLS AES performance test
  7. */
  8. #include <string.h>
  9. #include <stdio.h>
  10. #include <stdbool.h>
  11. #include <esp_system.h>
  12. #include "mbedtls/aes.h"
  13. #include "mbedtls/gcm.h"
  14. #include "unity.h"
  15. #include "sdkconfig.h"
  16. #include "esp_heap_caps.h"
  17. #include "test_utils.h"
  18. #include "ccomp_timer.h"
  19. TEST_CASE("mbedtls AES performance", "[aes][timeout=60]")
  20. {
  21. const unsigned CALLS = 256;
  22. const unsigned CALL_SZ = 32 * 1024;
  23. mbedtls_aes_context ctx;
  24. float elapsed_usec;
  25. uint8_t iv[16];
  26. uint8_t key[16];
  27. memset(iv, 0xEE, 16);
  28. memset(key, 0x44, 16);
  29. // allocate internal memory
  30. uint8_t *buf = heap_caps_malloc(CALL_SZ, MALLOC_CAP_DMA | MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  31. TEST_ASSERT_NOT_NULL(buf);
  32. mbedtls_aes_init(&ctx);
  33. mbedtls_aes_setkey_enc(&ctx, key, 128);
  34. ccomp_timer_start();
  35. for (int c = 0; c < CALLS; c++) {
  36. memset(buf, 0xAA, CALL_SZ);
  37. mbedtls_aes_crypt_cbc(&ctx, MBEDTLS_AES_ENCRYPT, CALL_SZ, iv, buf, buf);
  38. }
  39. elapsed_usec = ccomp_timer_stop();
  40. /* Sanity check: make sure the last ciphertext block matches
  41. what we expect to see.
  42. Last block produced via this Python:
  43. import os, binascii
  44. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  45. from cryptography.hazmat.backends import default_backend
  46. key = b'\x44' * 16
  47. iv = b'\xee' * 16
  48. cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
  49. encryptor = cipher.encryptor()
  50. ct = encryptor.update(b'\xaa' * 256 * 32 * 1024) + encryptor.finalize()
  51. print(binascii.hexlify(ct[-16:]))
  52. */
  53. const uint8_t expected_last_block[] = {
  54. 0x50, 0x81, 0xe0, 0xe1, 0x15, 0x2f, 0x14, 0xe9,
  55. 0x97, 0xa0, 0xc6, 0xe6, 0x36, 0xf3, 0x5c, 0x25,
  56. };
  57. TEST_ASSERT_EQUAL_HEX8_ARRAY(expected_last_block, buf + CALL_SZ - 16, 16);
  58. mbedtls_aes_free(&ctx);
  59. free(buf);
  60. // bytes/usec = MB/sec
  61. float mb_sec = (CALL_SZ * CALLS) / elapsed_usec;
  62. printf("Encryption rate %.3fMB/sec\n", mb_sec);
  63. #ifdef CONFIG_MBEDTLS_HARDWARE_AES
  64. // Don't put a hard limit on software AES performance
  65. TEST_PERFORMANCE_CCOMP_GREATER_THAN(AES_CBC_THROUGHPUT_MBSEC, "%.3fMB/sec", mb_sec);
  66. #endif
  67. }