Use BCryptGenRandom for Crypto::GetRandomBytes on Windows

The current implementation of Crypto::GetRandomBytes on Windows calls
`rand_s` repeatedly until the buffer is completely filled. However,
`BCryptGenRandom` already provides the similar functionality to fill the
whole buffer at once and thus there is no need to maintain a handcrafted
implementation any more.

TEST=ci

Change-Id: I52d990b01b59be872d825f2aa0e30b500a6d3e36
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/200160
Reviewed-by: Alexander Aprelev <aam@google.com>
Commit-Queue: Alexander Aprelev <aam@google.com>
This commit is contained in:
bdbai 2021-05-26 01:55:11 +00:00 committed by commit-bot@chromium.org
parent 987ab6a815
commit 1731050b29
2 changed files with 6 additions and 16 deletions

View file

@ -214,6 +214,7 @@ template("build_gen_snapshot") {
"Rpcrt4.lib",
"shlwapi.lib",
"winmm.lib",
"bcrypt.lib",
]
if (target_os != "winuwp") {
libs += [ "psapi.lib" ]
@ -784,6 +785,7 @@ template("dart_executable") {
"Rpcrt4.lib",
"shlwapi.lib",
"winmm.lib",
"bcrypt.lib",
]
}
}
@ -958,6 +960,7 @@ executable("run_vm_tests") {
"Rpcrt4.lib",
"shlwapi.lib",
"winmm.lib",
"bcrypt.lib",
]
}
}

View file

@ -2,31 +2,18 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#ifndef _CRT_RAND_S
#define _CRT_RAND_S
#endif
#include "platform/globals.h"
#if defined(HOST_OS_WINDOWS)
#include <bcrypt.h>
#include "bin/crypto.h"
namespace dart {
namespace bin {
bool Crypto::GetRandomBytes(intptr_t count, uint8_t* buffer) {
uint32_t num;
intptr_t read = 0;
while (read < count) {
if (rand_s(&num) != 0) {
return false;
}
for (int i = 0; i < 4 && read < count; i++) {
buffer[read] = num >> (i * 8);
read++;
}
}
return true;
return SUCCEEDED(BCryptGenRandom(NULL, buffer, (ULONG)count,
BCRYPT_USE_SYSTEM_PREFERRED_RNG));
}
} // namespace bin