ggentropy

A string formatting library for C++
Log | Files | Refs | README

commit afc77c3ca22407cf4304bec23e3490705e7cb912
parent 16ef369c8820b15a8d559d314149efaf0216f00a
Author: Michael Savage <mikejsavage@gmail.com>
Date:   Sat, 13 Mar 2021 13:49:47 +0200

Use BCryptGenRandom on Windows

Diffstat:
MREADME.md | 2+-
Mggentropy.cpp | 17+++--------------
2 files changed, 4 insertions(+), 15 deletions(-)

diff --git a/README.md b/README.md @@ -59,7 +59,7 @@ ggentropy uses the following functionality: | OS | Implementation | | - | - | -| Windows | [CryptGenRandom](https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptgenrandom) | +| Windows | [BCryptGenRandom](https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom) | | MacOS | [getentropy](https://opensource.apple.com/source/xnu/xnu-3789.21.4/bsd/man/man2/getentropy.2.auto.html) | | Linux | [getrandom](https://lwn.net/Articles/606141/) with a fallback to /dev/urandom if the syscall doesn't exist | | FreeBSD/OpenBSD/NetBSD | [arc4random_buf](https://man.openbsd.org/arc4random_buf) | diff --git a/ggentropy.cpp b/ggentropy.cpp @@ -66,26 +66,15 @@ static bool try_urandom( void * buf, size_t n ) { #if PLATFORM_WINDOWS -#pragma comment( lib, "advapi32.lib" ) +#pragma comment( lib, "bcrypt.lib" ) -#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN -#endif - #include <windows.h> -#include <wincrypt.h> +#include <bcrypt.h> bool ggentropy( void * buf, size_t n ) { assert( n <= 256 ); - - HCRYPTPROV provider; - if( CryptAcquireContext( &provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT ) == 0 ) - return false; - - int ok = CryptGenRandom( provider, n, ( BYTE * ) buf ); - CryptReleaseContext( provider, 0 ); - - return ok != 0; + return !FAILED( BCryptGenRandom( NULL, ( PUCHAR ) buf, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG ) ); } #elif PLATFORM_LINUX