windows-entropy-bcrypt.diff 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. Backported from: https://github.com/Mbed-TLS/mbedtls/pull/8047
  2. diff --git a/thirdparty/mbedtls/library/entropy_poll.c b/thirdparty/mbedtls/library/entropy_poll.c
  3. index 095fa9873d..3bbe88f88d 100644
  4. --- a/thirdparty/mbedtls/library/entropy_poll.c
  5. +++ b/thirdparty/mbedtls/library/entropy_poll.c
  6. @@ -41,32 +41,34 @@
  7. #if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
  8. -#if !defined(_WIN32_WINNT)
  9. -#define _WIN32_WINNT 0x0400
  10. -#endif
  11. #include <windows.h>
  12. -#include <wincrypt.h>
  13. +#include <bcrypt.h>
  14. +#include <intsafe.h>
  15. int mbedtls_platform_entropy_poll(void *data, unsigned char *output, size_t len,
  16. size_t *olen)
  17. {
  18. - HCRYPTPROV provider;
  19. ((void) data);
  20. *olen = 0;
  21. - if (CryptAcquireContext(&provider, NULL, NULL,
  22. - PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE) {
  23. - return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
  24. - }
  25. + /*
  26. + * BCryptGenRandom takes ULONG for size, which is smaller than size_t on
  27. + * 64-bit Windows platforms. Extract entropy in chunks of len (dependent
  28. + * on ULONG_MAX) size.
  29. + */
  30. + while (len != 0) {
  31. + unsigned long ulong_bytes =
  32. + (len > ULONG_MAX) ? ULONG_MAX : (unsigned long) len;
  33. +
  34. + if (!BCRYPT_SUCCESS(BCryptGenRandom(NULL, output, ulong_bytes,
  35. + BCRYPT_USE_SYSTEM_PREFERRED_RNG))) {
  36. + return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
  37. + }
  38. - if (CryptGenRandom(provider, (DWORD) len, output) == FALSE) {
  39. - CryptReleaseContext(provider, 0);
  40. - return MBEDTLS_ERR_ENTROPY_SOURCE_FAILED;
  41. + *olen += ulong_bytes;
  42. + len -= ulong_bytes;
  43. }
  44. - CryptReleaseContext(provider, 0);
  45. - *olen = len;
  46. -
  47. return 0;
  48. }
  49. #else /* _WIN32 && !EFIX64 && !EFI32 */