1 /* 2 * SPDX-FileCopyrightText: 2021 Espressif Systems (Shanghai) CO LTD 3 * 4 * SPDX-License-Identifier: Apache-2.0 5 */ 6 #include <stdio.h> 7 #include <string.h> 8 #include "unity.h" 9 #include "esp_system.h" 10 11 /* Note: these are just sanity tests, not the same as 12 entropy tests 13 */ 14 15 TEST_CASE("call esp_random()", "[random]") 16 { 17 const size_t NUM_RANDOM = 128; /* in most cases this is massive overkill */ 18 19 uint32_t zeroes = UINT32_MAX; 20 uint32_t ones = 0; 21 for (int i = 0; i < NUM_RANDOM - 1; i++) { 22 uint32_t r = esp_random(); 23 ones |= r; 24 zeroes &= ~r; 25 } 26 27 /* assuming a 'white' random distribution, we can expect 28 usually at least one time each bit will be zero and at 29 least one time each will be one. Statistically this 30 can still fail, just *very* unlikely to. */ 31 TEST_ASSERT_EQUAL_HEX32(0, zeroes); 32 TEST_ASSERT_EQUAL_HEX32(UINT32_MAX, ones); 33 } 34 35 TEST_CASE("call esp_fill_random()", "[random]") 36 { 37 const size_t NUM_BUF = 200; 38 const size_t BUF_SZ = 16; 39 uint8_t buf[NUM_BUF][BUF_SZ]; 40 uint8_t zero_buf[BUF_SZ]; 41 uint8_t one_buf[BUF_SZ]; 42 43 bzero(buf, sizeof(buf)); 44 bzero(one_buf, sizeof(zero_buf)); 45 memset(zero_buf, 0xFF, sizeof(one_buf)); 46 47 for (int i = 0; i < NUM_BUF; i++) { 48 esp_fill_random(buf[i], BUF_SZ); 49 } 50 /* No two 128-bit buffers should be the same 51 (again, statistically this could happen but it's very unlikely) */ 52 for (int i = 0; i < NUM_BUF; i++) { 53 for (int j = 0; j < NUM_BUF; j++) { 54 if (i != j) { 55 TEST_ASSERT_NOT_EQUAL(0, memcmp(buf[i], buf[j], BUF_SZ)); 56 } 57 } 58 } 59 60 /* Do the same all bits are zero and one at least once test across the buffers */ 61 for (int i = 0; i < NUM_BUF; i++) { 62 for (int x = 0; x < BUF_SZ; x++) { 63 zero_buf[x] &= ~buf[i][x]; 64 one_buf[x] |= buf[i][x]; 65 } 66 } 67 for (int x = 0; x < BUF_SZ; x++) { 68 TEST_ASSERT_EQUAL_HEX8(0, zero_buf[x]); 69 TEST_ASSERT_EQUAL_HEX8(0xFF, one_buf[x]); 70 } 71 } 72