Skip to content

Commit

Permalink
Make unpredictableSeed use CryptGenRandom (CryptoAPI) on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
0xEAB committed Jan 19, 2025
1 parent bea3184 commit a3b6342
Showing 1 changed file with 61 additions and 2 deletions.
63 changes: 61 additions & 2 deletions std/random.d
Original file line number Diff line number Diff line change
Expand Up @@ -1772,6 +1772,41 @@ else
}
}

version (Windows)
{
pragma(lib, "advapi32.lib"); // `std.registry` does so, too.

private bool wincryptGenRandom(T)(out T result) @trusted
{
import core.sys.windows.windef : DWORD;
import core.sys.windows.wincrypt;

HCRYPTPROV wincryptHandle;

const gotHandle = CryptAcquireContext(
&wincryptHandle,
MS_STRONG_PROV,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT,
);
if (!gotHandle)
return false;

scope (exit)
if (!CryptReleaseContext(&wincryptHandle, 0)) { /* ignore */ }

const gotRandom = CryptGenRandom(
wincryptHandle,
DWORD(T.sizeof),
cast(void*) &result,
);
if (!gotRandom)
return false;

return true;
}
}

/**
A "good" seed for initializing random number engines. Initializing
with $(D_PARAM unpredictableSeed) makes engines generate different
Expand All @@ -1788,7 +1823,19 @@ how excellent the source of entropy is.
*/
@property uint unpredictableSeed() @trusted nothrow @nogc
{
version (AnyARC4Random)
version (Windows)
{
uint result;
if (!wincryptGenRandom!UIntType(result))
{
version (none)
return fallbackSeed();
else
assert(false, "CryptAcquireContext() or CryptGenRandom() failed.");
}
return result;
}
else version (AnyARC4Random)
{
return arc4random();
}
Expand Down Expand Up @@ -1837,7 +1884,19 @@ if (isUnsigned!UIntType)
/// ditto
@property UIntType unpredictableSeed() @nogc nothrow @trusted
{
version (AnyARC4Random)
version (Windows)
{
UIntType result;
if (!wincryptGenRandom!UIntType(result))
{
version (none)
return fallbackSeed();
else
assert(false, "CryptAcquireContext() or CryptGenRandom() failed.");
}
return result;
}
else version (AnyARC4Random)
{
static if (UIntType.sizeof <= uint.sizeof)
{
Expand Down

0 comments on commit a3b6342

Please sign in to comment.