diff --git a/std/os/index.zig b/std/os/index.zig index 0a6f598a2..b5e0129da 100644 --- a/std/os/index.zig +++ b/std/os/index.zig @@ -130,16 +130,10 @@ pub fn getRandomBytes(buf: []u8) !void { try posixRead(fd, buf); }, Os.windows => { - var hCryptProv: windows.HCRYPTPROV = undefined; - if (windows.CryptAcquireContextA(&hCryptProv, null, null, windows.PROV_RSA_FULL, 0) == 0) { - const err = windows.GetLastError(); - return switch (err) { - else => unexpectedErrorWindows(err), - }; - } - defer _ = windows.CryptReleaseContext(hCryptProv, 0); - - if (windows.CryptGenRandom(hCryptProv, @intCast(windows.DWORD, buf.len), buf.ptr) == 0) { + // Call RtlGenRandom() instead of CryptGetRandom() on Windows + // https://github.com/rust-lang-nursery/rand/issues/111 + // https://bugzilla.mozilla.org/show_bug.cgi?id=504270 + if (!windows.RtlGenRandom(buf.ptr, buf.len)) { const err = windows.GetLastError(); return switch (err) { else => unexpectedErrorWindows(err), @@ -159,8 +153,14 @@ pub fn getRandomBytes(buf: []u8) !void { } test "os.getRandomBytes" { - var buf: [50]u8 = undefined; - try getRandomBytes(buf[0..]); + var buf_a: [50]u8 = undefined; + var buf_b: [50]u8 = undefined; + // Call Twice + try getRandomBytes(buf_a[0..]); + try getRandomBytes(buf_b[0..]); + + // Check if random (not 100% conclusive) + assert( !mem.eql(u8, buf_a, buf_b) ); } /// Raises a signal in the current kernel thread, ending its execution. diff --git a/std/os/windows/advapi32.zig b/std/os/windows/advapi32.zig index dcb5a636e..64a820a3b 100644 --- a/std/os/windows/advapi32.zig +++ b/std/os/windows/advapi32.zig @@ -28,3 +28,8 @@ pub extern "advapi32" stdcallcc fn RegOpenKeyExW(hKey: HKEY, lpSubKey: LPCWSTR, pub extern "advapi32" stdcallcc fn RegQueryValueExW(hKey: HKEY, lpValueName: LPCWSTR, lpReserved: LPDWORD, lpType: LPDWORD, lpData: LPBYTE, lpcbData: LPDWORD,) LSTATUS; + +// RtlGenRandom is known as SystemFunction036 under advapi32 +// http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx */ +pub extern "advapi32" stdcallcc fn SystemFunction036(output: PVOID, length: ULONG_PTR) BOOL; +pub const RtlGenRandom = SystemFunction036; diff --git a/std/os/windows/util.zig b/std/os/windows/util.zig index dda9ce7a8..c9d2c3c3e 100644 --- a/std/os/windows/util.zig +++ b/std/os/windows/util.zig @@ -166,7 +166,7 @@ pub fn windowsUnloadDll(hModule: windows.HMODULE) void { } test "InvalidDll" { - if (builtin.os != builtin.Os.windows) return; + if (builtin.os != builtin.Os.windows) return error.SkipZigTest; const DllName = "asdf.dll"; const allocator = std.debug.global_allocator;