test_sha_perf.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /* mbedTLS SHA performance test
  2. */
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include <stdbool.h>
  6. #include "mbedtls/sha256.h"
  7. #include "unity.h"
  8. #include "sdkconfig.h"
  9. #include "esp_heap_caps.h"
  10. #include "test_utils.h"
  11. #include "sodium/utils.h"
  12. #include "ccomp_timer.h"
  13. TEST_CASE("mbedtls SHA performance", "[aes]")
  14. {
  15. const unsigned CALLS = 256;
  16. const unsigned CALL_SZ = 16 * 1024;
  17. mbedtls_sha256_context sha256_ctx;
  18. float elapsed_usec;
  19. unsigned char sha256[32];
  20. // allocate internal memory
  21. uint8_t *buf = heap_caps_malloc(CALL_SZ, MALLOC_CAP_DMA | MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
  22. TEST_ASSERT_NOT_NULL(buf);
  23. memset(buf, 0x55, CALL_SZ);
  24. mbedtls_sha256_init(&sha256_ctx);
  25. ccomp_timer_start();
  26. TEST_ASSERT_EQUAL(0, mbedtls_sha256_starts_ret(&sha256_ctx, false));
  27. for (int c = 0; c < CALLS; c++) {
  28. TEST_ASSERT_EQUAL(0, mbedtls_sha256_update_ret(&sha256_ctx, buf, CALL_SZ));
  29. }
  30. TEST_ASSERT_EQUAL(0, mbedtls_sha256_finish_ret(&sha256_ctx, sha256));
  31. elapsed_usec = ccomp_timer_stop();
  32. free(buf);
  33. mbedtls_sha256_free(&sha256_ctx);
  34. /* Check the result. Reference value can be calculated using:
  35. * dd if=/dev/zero bs=$((16*1024)) count=256 | tr '\000' '\125' | sha256sum
  36. */
  37. const char *expected_hash = "c88df2638fb9699abaad05780fa5e0fdb6058f477069040eac8bed3231286275";
  38. char hash_str[sizeof(sha256) * 2 + 1];
  39. sodium_bin2hex(hash_str, sizeof(hash_str), sha256, sizeof(sha256));
  40. TEST_ASSERT_EQUAL_STRING(expected_hash, hash_str);
  41. // bytes/usec = MB/sec
  42. float mb_sec = (CALL_SZ * CALLS) / elapsed_usec;
  43. printf("SHA256 rate %.3fMB/sec\n", mb_sec);
  44. #ifdef CONFIG_MBEDTLS_HARDWARE_SHA
  45. // Don't put a hard limit on software SHA performance
  46. TEST_PERFORMANCE_CCOMP_GREATER_THAN(SHA256_THROUGHPUT_MBSEC, "%.3fMB/sec", mb_sec);
  47. #endif
  48. }