blob: 953d9caf069e02d5483dc446d368d0a05bdbbba4 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2017 The Chromium Authors
Scott Graham4ffd63b52017-06-01 18:03:332// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/rand_util.h"
6
Scott Grahamfe0e9f462017-09-18 21:25:047#include <zircon/syscalls.h>
Scott Graham4ffd63b52017-06-01 18:03:338
Daniel Chengb6bbf5a62022-09-09 18:26:349#include <atomic>
10
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"
14
Scott Graham4ffd63b52017-06-01 18:03:3315namespace base {
16
Daniel Chengb6bbf5a62022-09-09 18:26:3417namespace internal {
18
19namespace {
20
21// The BoringSSl helpers are duplicated in rand_util_posix.cc and
22// rand_util_win.cc.
23std::atomic<bool> g_use_boringssl;
24
25const Feature kUseBoringSSLForRandBytes{"UseBoringSSLForRandBytes",
26 FEATURE_DISABLED_BY_DEFAULT};
27
28} // namespace
29
30void ConfigureBoringSSLBackedRandBytesFieldTrial() {
31 g_use_boringssl.store(FeatureList::IsEnabled(kUseBoringSSLForRandBytes),
32 std::memory_order_relaxed);
33}
34
35bool UseBoringSSLForRandBytes() {
36 return g_use_boringssl.load(std::memory_order_relaxed);
37}
38
39} // namespace internal
40
Scott Graham4ffd63b52017-06-01 18:03:3341void RandBytes(void* output, size_t output_length) {
Daniel Chengb6bbf5a62022-09-09 18:26:3442 if (internal::UseBoringSSLForRandBytes()) {
43 // Ensure BoringSSL is initialized so it can use things like RDRAND.
44 CRYPTO_library_init();
45 // BoringSSL's RAND_bytes always returns 1. Any error aborts the program.
46 (void)RAND_bytes(static_cast<uint8_t*>(output), output_length);
47 return;
48 }
49
Wez53049622018-06-29 05:46:4950 zx_cprng_draw(output, output_length);
Scott Graham4ffd63b52017-06-01 18:03:3351}
52
Egor Pasko1c7e6242022-09-20 12:45:3953namespace internal {
54
55double RandDoubleAvoidAllocation() {
56 uint64_t number;
57 zx_cprng_draw(&number, sizeof(number));
58 // This transformation is explained in rand_util.cc.
59 return (number >> 11) * 0x1.0p-53;
60}
61
62} // namespace internal
63
Scott Graham