Skip to content

Commit

Permalink
Implement get_random_bytes() for MSVC
Browse files Browse the repository at this point in the history
  • Loading branch information
cmb69 committed Dec 10, 2024
1 parent 7fcc3e8 commit dfab9d3
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion lib/util-get-random-bytes.c
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef _MSC_VER
#include <bcrypt.h>
#endif

/* If we have O_CLOEXEC, we use it, but if we don't, we don't worry
about it. */
Expand All @@ -52,7 +55,10 @@
getentropy() and enforced regardless of the actual back-end in use).
If we fall all the way back to /dev/urandom, we open and close it on
each call. */
each call.
With MSVC we fall back to BCryptGenRandom(), and open and close the
provider on each call. */

bool
get_random_bytes(void *buf, size_t buflen)
Expand Down Expand Up @@ -146,6 +152,27 @@ get_random_bytes(void *buf, size_t buflen)
}
}
#endif

#ifdef _MSC_VER
static bool bcrypt_doesnt_work;
if (!bcrypt_doesnt_work)
{
BCRYPT_ALG_HANDLE algo;
NTSTATUS res;
res = BCryptOpenAlgorithmProvider(&algo, BCRYPT_RNG_ALGORITHM, NULL, 0);
if (!BCRYPT_SUCCESS(res))
bcrypt_doesnt_work = true;
else
{
res = BCryptGenRandom(algo, buf, (ULONG) buflen, 0);
if (!BCRYPT_SUCCESS(res))
bcrypt_doesnt_work = true;

BCryptCloseAlgorithmProvider(algo, 0);
return !bcrypt_doesnt_work;
}
}
#endif
#endif /* no arc4random_buf */

/* if we get here, we're just completely hosed */
Expand Down

0 comments on commit dfab9d3

Please sign in to comment.