Created
April 28, 2021 19:50
-
-
Save kachsheev/86b7cd7e3ee6d36893c8924b3288ba65 to your computer and use it in GitHub Desktop.
WinAPI Generate Random class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From stackoverflow: https://stackoverflow.com/a/21429737 | |
#include <wincrypt.h> | |
class RandomSequence | |
{ | |
HCRYPTPROV hProvider; | |
public: | |
RandomSequence(void) : hProvider(NULL) { | |
if (FALSE == CryptAcquireContext(&hProvider, NULL, NULL, PROV_RSA_FULL, 0)) { | |
// failed, should we try to create a default provider? | |
if (NTE_BAD_KEYSET == GetLastError()) { | |
if (FALSE == CryptAcquireContext(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) { | |
// ensure the provider is NULL so we could use a backup plan | |
hProvider = NULL; | |
} | |
} | |
} | |
} | |
~RandomSequence(void) { | |
if (NULL != hProvider) { | |
CryptReleaseContext(hProvider, 0U); | |
} | |
} | |
BOOL generate(BYTE* buf, DWORD len) { | |
if (NULL != hProvider) { | |
return CryptGenRandom(hProvider, len, buf); | |
} | |
return FALSE; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment