mbed.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #include <mbedtls/ctr_drbg.h>
  2. #include <mbedtls/entropy.h>
  3. #if defined(MBEDTLS_ENTROPY_C)
  4. static int
  5. hydro_random_init(void)
  6. {
  7. mbedtls_entropy_context entropy;
  8. uint16_t pos = 0;
  9. mbedtls_entropy_init(&entropy);
  10. // Pull data directly out of the entropy pool for the state, as it's small enough.
  11. if (mbedtls_entropy_func(&entropy, (uint8_t *) &hydro_random_context.counter,
  12. sizeof hydro_random_context.counter) != 0) {
  13. return -1;
  14. }
  15. // mbedtls_entropy_func can't provide more than MBEDTLS_ENTROPY_BLOCK_SIZE in one go.
  16. // This constant depends of mbedTLS configuration (whether the PRNG is backed by SHA256/SHA512
  17. // at this time) Therefore, if necessary, we get entropy multiple times.
  18. do {
  19. const uint8_t dataLeftToConsume = gimli_BLOCKBYTES - pos;
  20. const uint8_t currentChunkSize = (dataLeftToConsume > MBEDTLS_ENTROPY_BLOCK_SIZE)
  21. ? MBEDTLS_ENTROPY_BLOCK_SIZE
  22. : dataLeftToConsume;
  23. // Forces mbedTLS to fetch fresh entropy, then get some to feed libhydrogen.
  24. if (mbedtls_entropy_gather(&entropy) != 0 ||
  25. mbedtls_entropy_func(&entropy, &hydro_random_context.state[pos], currentChunkSize) !=
  26. 0) {
  27. return -1;
  28. }
  29. pos += MBEDTLS_ENTROPY_BLOCK_SIZE;
  30. } while (pos < gimli_BLOCKBYTES);
  31. mbedtls_entropy_free(&entropy);
  32. return 0;
  33. }
  34. #else
  35. #error Need an entropy source
  36. #endif