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