test_sha.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "esp_types.h"
  5. #include "esp32c3/clk.h"
  6. #include "esp_log.h"
  7. #include "esp_timer.h"
  8. #include "esp_heap_caps.h"
  9. #include "idf_performance.h"
  10. #include "unity.h"
  11. #include "test_utils.h"
  12. #include "mbedtls/sha1.h"
  13. #include "mbedtls/sha256.h"
  14. #include "sha/sha_dma.h"
  15. /* Note: Most of the SHA functions are called as part of mbedTLS, so
  16. are tested as part of mbedTLS tests. Only esp_sha() is different.
  17. */
  18. #define TAG "sha_test"
  19. TEST_CASE("Test esp_sha()", "[hw_crypto]")
  20. {
  21. const size_t BUFFER_SZ = 32 * 1024 + 6; // NB: not an exact multiple of SHA block size
  22. int64_t begin, end;
  23. uint32_t us_sha1;
  24. uint8_t sha1_result[20] = { 0 };
  25. void *buffer = heap_caps_malloc(BUFFER_SZ, MALLOC_CAP_8BIT|MALLOC_CAP_INTERNAL);
  26. TEST_ASSERT_NOT_NULL(buffer);
  27. memset(buffer, 0xEE, BUFFER_SZ);
  28. const uint8_t sha1_expected[20] = { 0xc7, 0xbb, 0xd3, 0x74, 0xf2, 0xf6, 0x20, 0x86,
  29. 0x61, 0xf4, 0x50, 0xd5, 0xf5, 0x18, 0x44, 0xcc,
  30. 0x7a, 0xb7, 0xa5, 0x4a };
  31. begin = esp_timer_get_time();
  32. esp_sha(SHA1, buffer, BUFFER_SZ, sha1_result);
  33. end = esp_timer_get_time();
  34. TEST_ASSERT_EQUAL_HEX8_ARRAY(sha1_expected, sha1_result, sizeof(sha1_expected));
  35. us_sha1 = end - begin;
  36. ESP_LOGI(TAG, "esp_sha() 32KB SHA1 in %u us", us_sha1);
  37. free(buffer);
  38. TEST_PERFORMANCE_CCOMP_LESS_THAN(TIME_SHA1_32KB, "%dus", us_sha1);
  39. }
  40. TEST_CASE("Test esp_sha() function with long input", "[hw_crypto]")
  41. {
  42. const void* ptr;
  43. spi_flash_mmap_handle_t handle;
  44. uint8_t sha1_espsha[20] = { 0 };
  45. uint8_t sha1_mbedtls[20] = { 0 };
  46. uint8_t sha256_espsha[32] = { 0 };
  47. uint8_t sha256_mbedtls[32] = { 0 };
  48. const size_t LEN = 1024 * 1024;
  49. /* mmap() 1MB of flash, we don't care what it is really */
  50. esp_err_t err = spi_flash_mmap(0x0, LEN, SPI_FLASH_MMAP_DATA, &ptr, &handle);
  51. TEST_ASSERT_EQUAL_HEX32(ESP_OK, err);
  52. TEST_ASSERT_NOT_NULL(ptr);
  53. /* Compare esp_sha() result to the mbedTLS result, should always be the same */
  54. esp_sha(SHA1, ptr, LEN, sha1_espsha);
  55. int r = mbedtls_sha1_ret(ptr, LEN, sha1_mbedtls);
  56. TEST_ASSERT_EQUAL(0, r);
  57. esp_sha(SHA2_256, ptr, LEN, sha256_espsha);
  58. r = mbedtls_sha256_ret(ptr, LEN, sha256_mbedtls, 0);
  59. TEST_ASSERT_EQUAL(0, r);
  60. TEST_ASSERT_EQUAL_MEMORY_MESSAGE(sha1_espsha, sha1_mbedtls, sizeof(sha1_espsha), "SHA1 results should match");
  61. TEST_ASSERT_EQUAL_MEMORY_MESSAGE(sha256_espsha, sha256_mbedtls, sizeof(sha256_espsha), "SHA256 results should match");
  62. }