esp_random.c 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdlib.h>
  7. #include <time.h>
  8. #include <stdint.h>
  9. #include <assert.h>
  10. #include <string.h>
  11. #include <sys/param.h>
  12. #include "esp_log.h"
  13. static const char* TAG = "esp-random";
  14. static void __attribute__((constructor)) esp_random_init(void)
  15. {
  16. srand(time(NULL));
  17. ESP_LOGW(TAG, "esp_random do not provide a cryptographically secure numbers on Linux, and should never be used for anything security related");
  18. }
  19. uint32_t esp_random(void)
  20. {
  21. /* Adding INT32_MAX to shift the results such that after conversion to uint32_t we still get 32 bits of random data */
  22. return (rand() + INT32_MAX);
  23. }
  24. void esp_fill_random(void *buf, size_t len)
  25. {
  26. assert(buf != NULL);
  27. uint8_t *buf_bytes = (uint8_t *)buf;
  28. while (len > 0) {
  29. uint32_t word = esp_random();
  30. uint32_t to_copy = MIN(sizeof(word), len);
  31. memcpy(buf_bytes, &word, to_copy);
  32. buf_bytes += to_copy;
  33. len -= to_copy;
  34. }
  35. }