test_random.c 2.0 KB

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