Skip to content

Instantly share code, notes, and snippets.

@kachsheev
Created April 28, 2021 19:50
Show Gist options
  • Save kachsheev/86b7cd7e3ee6d36893c8924b3288ba65 to your computer and use it in GitHub Desktop.
Save kachsheev/86b7cd7e3ee6d36893c8924b3288ba65 to your computer and use it in GitHub Desktop.
WinAPI Generate Random class
// 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