1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/rand_util.h"
7 #include <zircon/syscalls.h>
11 #include "base/feature_list.h"
12 #include "third_party/boringssl/src/include/openssl/crypto.h"
13 #include "third_party/boringssl/src/include/openssl/rand.h"
21 // The BoringSSl helpers are duplicated in rand_util_posix.cc and
23 std::atomic<bool> g_use_boringssl;
25 BASE_FEATURE(kUseBoringSSLForRandBytes,
26 "UseBoringSSLForRandBytes",
27 FEATURE_DISABLED_BY_DEFAULT);
31 void ConfigureBoringSSLBackedRandBytesFieldTrial() {
32 g_use_boringssl.store(FeatureList::IsEnabled(kUseBoringSSLForRandBytes),
33 std::memory_order_relaxed);
36 bool UseBoringSSLForRandBytes() {
37 return g_use_boringssl.load(std::memory_order_relaxed);
40 } // namespace internal
42 void RandBytes(void* output, size_t output_length) {
43 if (internal::UseBoringSSLForRandBytes()) {
44 // Ensure BoringSSL is initialized so it can use things like RDRAND.
45 CRYPTO_library_init();
46 // BoringSSL's RAND_bytes always returns 1. Any error aborts the program.
47 (void)RAND_bytes(static_cast<uint8_t*>(output), output_length);
51 zx_cprng_draw(output, output_length);
56 double RandDoubleAvoidAllocation() {
58 zx_cprng_draw(&number, sizeof(number));
59 // This transformation is explained in rand_util.cc.
60 return (number >> 11) * 0x1.0p-53;
63 } // namespace internal