blob: b9e5eaa93df3ffe1feb1fab0b75b7f6ab1d2192b [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
Mark Mentovai5d6e7632023-08-11 17:21:439#include <atomic>
10
11#include "base/feature_list.h"
Daniel Chengb6bbf5a62022-09-09 18:26:3412#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
Mark Mentovai5d6e7632023-08-11 17:21:4317namespace 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
25BASE_FEATURE(kUseBoringSSLForRandBytes,
26 "UseBoringSSLForRandBytes",
27 FEATURE_DISABLED_BY_DEFAULT);
28
29} // namespace
30
31void ConfigureBoringSSLBackedRandBytesFieldTrial() {
32 g_use_boringssl.store(FeatureList::IsEnabled(kUseBoringSSLForRandBytes),
33 std::memory_order_relaxed);
34}
35
36bool UseBoringSSLForRandBytes() {
37 return g_use_boringssl.load(std::memory_order_relaxed);
38}
39
40} // namespace internal
41
Scott Graham4ffd63b52017-06-01 18:03:3342void RandBytes(void* output, size_t output_length) {
Mark Mentovai5d6e7632023-08-11 17:21:4343 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);
48 return;
49 }
50
51 zx_cprng_draw(output, output_length);
Scott Graham4ffd63b52017-06-01 18:03:3352}
53
Egor Pasko1c7e6242022-09-20 12:45:3954namespace internal {
55
56double RandDoubleAvoidAllocation() {
57 uint64_t number;
58 zx_cprng_draw(&number, sizeof(number));
59 // This transformation is explained in rand_util.cc.
60 return (number >> 11) * 0x1.0p-53;
61}
62
63} // namespace internal
64
Scott Graham4ffd63b52017-06-01 18:03:3365} // namespace base