Last active
January 29, 2018 14:36
-
-
Save simon-p-r/62929b659fcd93ede6c0c6319d87f8a8 to your computer and use it in GitHub Desktop.
Windows generate random bytes to uint64_t
This file contains 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
// generate random unsigned 64bit integer | |
#ifdef _WIN32 | |
#define __alignof__ __alignof | |
#define snprintf(buf, bufSize, format, arg) _snprintf_s(buf, bufSize, _TRUNCATE, format, arg) | |
#define strtoll _strtoi64 | |
#define strtoull _strtoui64 | |
#define PRId64 "lld" | |
#define PRIu64 "llu" | |
#include <windows.h> | |
#pragma comment(lib, "advapi32.lib") | |
#include <Wincrypt.h> | |
#endif | |
uint64_t crypto_generate_rand() { | |
bool result = false; | |
HCRYPTPROV prov = 0; | |
BYTE pbBuffer[8] = {0}; | |
DWORD dwLength; | |
uint64_t randval = 0; | |
if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) { | |
return randval; | |
} | |
if (!CryptGenRandom(prov, dwLength, pbBuffer)) { | |
if (!CryptReleaseContext(prov, 0)) { | |
printf("Unable to release context\n"); | |
return randval; | |
} | |
printf("Released crypto context\n"); | |
return randval; | |
} | |
if (!CryptReleaseContext(prov, 0)) { | |
printf("Unable to release context\n"); | |
return randval; | |
} | |
randval = *(uint64_t *)pbBuffer; | |
return randval; | |
}; | |
int main () { | |
uint64_t rand = crypto_gen_rand(); | |
printf("%\n" PRId64, rand); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment