test_aes_perf.c 2.2 KB

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