0

Remove use of the pointer version of RandBytes, use span always

The pointer-based crypto::RandBytes() overload can't be removed until
nearby stops using it: https://crrev.com/c/5529443 will do this.

The pointer-based base::RandBytes() will be removed next.

Bug: 40284755
Change-Id: I72c79e23e120f988b091dd2576de180a1c60d2b7
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/5514816
Commit-Queue: danakj <danakj@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Owners-Override: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1298850}
This commit is contained in:
danakj
2024-05-09 20:38:44 +00:00
committed by Chromium LUCI CQ
parent b7f484b121
commit 95305d27de
84 changed files with 227 additions and 232 deletions
base
chrome
browser
installer
services
chromeos/ash/components/nearby/common/connections_manager
components
browsing_topics
chromeos_camera
media_router
common
providers
metrics
network_session_configurator
optimization_guide
reporting
search_engines
storage_monitor
sync
engine
loopback_server
nigori
trusted_vault
content/browser/webauth
crypto
device/fido
gin
gpu/command_buffer/common
media/filters
mojo
net
ppapi/shared_impl
remoting/host
rlz/lib
skia/ext
storage
browser
common
third_party

@ -42,6 +42,25 @@ void Extend(std::vector<T>& dst, span<const T, N> src) {
dst.insert(dst.end(), src.begin(), src.end());
}
// Append to |dst| all elements of |src| by copying them out of |src|. |src| is
// not changed.
//
// # Implementation note on convertible_to
// This overload allows implicit conversions to `span<T>`, in the same way that
// would occur if we received a non-template `span<int>`. This would not be
// possible by just receiving `span<T>` as the templated `T` can not be deduced
// (even though it is fixed by the deduction from the `vector<T>` parameter).
// The overloads above do not allow implicit conversion, but do accept
// fixed-size spans without losing the fixed-size `N`. They can not be written
// in the same format as the `N` would not be deducible for the `convertible_to`
// check.
template <typename T, typename S>
requires(std::convertible_to<S, span<const T>>)
void Extend(std::vector<T>& dst, S&& src) {
span<const T> src_span = src;
dst.insert(dst.end(), src_span.begin(), src_span.end());
}
} // namespace base
#endif // BASE_CONTAINERS_EXTEND_H_

@ -131,6 +131,11 @@ TEST(ExtendTest, ExtendWithSpan) {
// Selects overload for span<uint8_t, dynamic_extent>.
Extend(dst, span(kMutVector));
EXPECT_THAT(dst, ElementsAre(3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 10, 11));
// Input is convertible to span.
Extend(dst, kRawArray);
EXPECT_THAT(dst,
ElementsAre(3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 10, 11, 3, 4, 5));
}
} // namespace base

@ -51,7 +51,7 @@ void RunTest(const char* hash_name,
TimeDelta total_test_time;
{
std::vector<uint8_t> buf(len);
RandBytes(buf.data(), len);
RandBytes(buf);
for (int i = 0; i < kNumRuns; ++i) {
const auto start = TimeTicks::Now();

@ -11,6 +11,7 @@
#include <memory>
#include "base/containers/heap_array.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/files/memory_mapped_file.h"
@ -923,8 +924,8 @@ TEST(FilePersistentMemoryAllocatorTest, AcceptableTest) {
local.MakeIterable(local.Allocate(1, 1));
local.MakeIterable(local.Allocate(11, 11));
const size_t minsize = local.used();
std::unique_ptr<char[]> garbage(new char[minsize]);
RandBytes(garbage.get(), minsize);
auto garbage = HeapArray<uint8_t>::Uninit(minsize);
RandBytes(garbage);
std::unique_ptr<MemoryMappedFile> mmfile;
char filename[100];
@ -988,7 +989,7 @@ TEST(FilePersistentMemoryAllocatorTest, AcceptableTest) {
{
File writer(file_path, File::FLAG_CREATE | File::FLAG_WRITE);
ASSERT_TRUE(writer.IsValid());
writer.Write(0, (const char*)garbage.get(), filesize);
writer.Write(0, garbage.first(filesize));
}
ASSERT_TRUE(PathExists(file_path));

@ -30,7 +30,7 @@ std::atomic<bool> g_subsampling_never_sample = false;
uint64_t RandUint64() {
uint64_t number;
RandBytes(&number, sizeof(number));
RandBytes(base::byte_span_from_ref(number));
return number;
}
@ -111,17 +111,14 @@ uint64_t RandGenerator(uint64_t range) {
}
std::string RandBytesAsString(size_t length) {
DCHECK_GT(length, 0u);
std::string result(length, '\0');
RandBytes(result.data(), length);
RandBytes(as_writable_byte_span(result));
return result;
}
std::vector<uint8_t> RandBytesAsVector(size_t length) {
std::vector<uint8_t> result(length);
if (result.size()) {
RandBytes(result);
}
RandBytes(result);
return result;
}

@ -84,14 +84,17 @@ BASE_EXPORT double BitsToOpenEndedUnitInterval(uint64_t bits);
// [0, 1). Thread-safe.
BASE_EXPORT float BitsToOpenEndedUnitIntervalF(uint64_t bits);
// Fills `output` with random data. Thread-safe.
// Fills `output` with cryptographically secure random data. Thread-safe.
//
// Although implementations are required to use a cryptographically secure
// random number source, code outside of base/ that relies on this should use
// crypto::RandBytes instead to ensure the requirement is easily discoverable.
BASE_EXPORT void RandBytes(span<uint8_t> output);
// TODO(crbug.com/40284755): Migrate callers to the span version.
BASE_EXPORT void RandBytes(void* output, size_t output_length);
// // TODO(40284755): This overload will be removed, do not use.
inline void RandBytes(void* output, size_t output_length) {
UNSAFE_BUFFERS(span(static_cast<uint8_t*>(output), output_length));
}
// Creates a vector of `length` bytes, fills it with random data, and returns
// it. Thread-safe.
@ -101,9 +104,9 @@ BASE_EXPORT void RandBytes(void* output, size_t output_length);
// crypto::RandBytes instead to ensure the requirement is easily discoverable.
BASE_EXPORT std::vector<uint8_t> RandBytesAsVector(size_t length);
// DEPRECATED. Prefert RandBytesAsVector() above.
// DEPRECATED. Prefer RandBytesAsVector() above.
// Fills a string of length |length| with random data and returns it.
// |length| should be nonzero. Thread-safe.
// Thread-safe.
//
// Note that this is a variation of |RandBytes| with a different return type.
// The returned string is likely not ASCII/UTF-8. Use with care.

@ -57,10 +57,6 @@ void RandBytes(span<uint8_t> output) {
zx_cprng_draw(output.data(), output.size());
}
void RandBytes(void* output, size_t output_length) {
RandBytes(make_span(static_cast<uint8_t*>(output), output_length));
}
namespace internal {
double RandDoubleAvoidAllocation() {

@ -23,8 +23,4 @@ void RandBytes(span<uint8_t> output) {
}
}
void RandBytes(void* output, size_t output_length) {
RandBytes(make_span(static_cast<uint8_t*>(output), output_length));
}
} // namespace base

@ -181,7 +181,7 @@ bool UseBoringSSLForRandBytes() {
namespace {
void RandBytes(span<uint8_t> output, bool avoid_allocation) {
void RandBytesInternal(span<uint8_t> output, bool avoid_allocation) {
#if !BUILDFLAG(IS_NACL)
// The BoringSSL experiment takes priority over everything else.
if (!avoid_allocation && internal::UseBoringSSLForRandBytes()) {
@ -228,8 +228,7 @@ namespace internal {
double RandDoubleAvoidAllocation() {
uint64_t number;
RandBytes(as_writable_bytes(make_span(&number, 1u)),
/*avoid_allocation=*/true);
RandBytesInternal(byte_span_from_ref(number), /*avoid_allocation=*/true);
// This transformation is explained in rand_util.cc.
return (number >> 11) * 0x1.0p-53;
}
@ -237,11 +236,7 @@ double RandDoubleAvoidAllocation() {
} // namespace internal
void RandBytes(span<uint8_t> output) {
RandBytes(output, /*avoid_allocation=*/false);
}
void RandBytes(void* output, size_t output_length) {
RandBytes(make_span(static_cast<uint8_t*>(output), output_length));
RandBytesInternal(output, /*avoid_allocation=*/false);
}
int GetUrandomFD() {

@ -139,7 +139,6 @@ TEST(RandUtilTest, RandBytes) {
// Verify that calling base::RandBytes with an empty buffer doesn't fail.
TEST(RandUtilTest, RandBytes0) {
base::RandBytes(span<uint8_t>());
base::RandBytes(nullptr, 0);
}
TEST(RandUtilTest, RandBytesAsVector) {
@ -260,10 +259,11 @@ TEST(RandUtilTest, DISABLED_RandBytesPerf) {
const int kTestIterations = 10;
const size_t kTestBufferSize = 1 * 1024 * 1024;
std::unique_ptr<uint8_t[]> buffer(new uint8_t[kTestBufferSize]);
std::array<uint8_t, kTestBufferSize> buffer;
const base::TimeTicks now = base::TimeTicks::Now();
for (int i = 0; i < kTestIterations; ++i)
base::RandBytes(make_span(buffer.get(), kTestBufferSize));
for (int i = 0; i < kTestIterations; ++i) {
base::RandBytes(buffer);
}
const base::TimeTicks end = base::TimeTicks::Now();
LOG(INFO) << "RandBytes(" << kTestBufferSize

@ -70,7 +70,7 @@ decltype(&ProcessPrng) GetProcessPrng() {
return process_prng_fn;
}
void RandBytes(span<uint8_t> output, bool avoid_allocation) {
void RandBytesInternal(span<uint8_t> output, bool avoid_allocation) {
if (!avoid_allocation && internal::UseBoringSSLForRandBytes()) {
// Ensure BoringSSL is initialized so it can use things like RDRAND.
CRYPTO_library_init();
@ -89,20 +89,15 @@ void RandBytes(span<uint8_t> output, bool avoid_allocation) {
} // namespace
void RandBytes(span<uint8_t> output) {
RandBytes(output, /*avoid_allocation=*/false);
}
void RandBytes(void* output, size_t output_length) {
RandBytes(make_span(static_cast<uint8_t*>(output), output_length),
/*avoid_allocation=*/false);
RandBytesInternal(output, /*avoid_allocation=*/false);
}
namespace internal {
double RandDoubleAvoidAllocation() {
uint64_t number;
RandBytes(as_writable_bytes(make_span(&number, 1u)),
/*avoid_allocation=*/true);
RandBytesInternal(byte_span_from_ref(number),
/*avoid_allocation=*/true);
// This transformation is explained in rand_util.cc.
return (number >> 11) * 0x1.0p-53;
}

@ -70,7 +70,7 @@ __stack_chk_fail() {
void NO_STACK_PROTECTOR ResetStackCanaryIfPossible() {
uintptr_t canary;
base::RandBytes(as_writable_bytes(make_span(&canary, 1u)));
base::RandBytes(base::byte_span_from_ref(canary));
// First byte should be the null byte for string functions.
canary &= ~static_cast<uintptr_t>(0xff);

@ -463,7 +463,7 @@ inline typename string_type::value_type* WriteIntoT(string_type* str,
DCHECK_GE(length_with_null, 1u);
str->reserve(length_with_null);
str->resize(length_with_null - 1);
return &((*str)[0]);
return str->data();
}
// Generic version for all JoinString overloads. |list_type| must be a sequence

@ -56,7 +56,7 @@ bool CreatePairImpl(ScopedHandle* socket_a,
do {
unsigned long rnd_name;
RandBytes(&rnd_name, sizeof(rnd_name));
RandBytes(byte_span_from_ref(rnd_name));
swprintf(name, kPipePathMax,
kPipeNameFormat,

@ -28,7 +28,7 @@ Token Token::CreateRandom() {
// Use base::RandBytes instead of crypto::RandBytes, because crypto calls the
// base version directly, and to prevent the dependency from base/ to crypto/.
base::RandBytes(&token, sizeof(token));
RandBytes(byte_span_from_ref(token));
CHECK(!token.is_zero());
@ -36,7 +36,7 @@ Token Token::CreateRandom() {
}
std::string Token::ToString() const {
return base::StringPrintf("%016" PRIX64 "%016" PRIX64, words_[0], words_[1]);
return StringPrintf("%016" PRIX64 "%016" PRIX64, words_[0], words_[1]);
}
// static

@ -232,7 +232,7 @@ std::optional<Sid> Sid::FromPSID(PSID sid) {
Sid Sid::GenerateRandomSid() {
DWORD sub_authorities[4] = {};
RandBytes(&sub_authorities, sizeof(sub_authorities));
RandBytes(as_writable_byte_span(sub_authorities));
return FromSubAuthorities(SECURITY_NULL_SID_AUTHORITY,
std::size(sub_authorities), sub_authorities);
}

@ -445,7 +445,7 @@ bool SoftBindAttestationFlowImpl::GenerateLeafCert(
uint8_t* cert_bytes;
size_t cert_len;
uint64_t serial_number;
crypto::RandBytes(&serial_number, sizeof(serial_number));
crypto::RandBytes(base::byte_span_from_ref(serial_number));
if (!CBB_init(cbb.get(), 64) ||
!CBB_add_asn1(cbb.get(), &cert, CBS_ASN1_SEQUENCE) ||
!CBB_add_asn1(&cert, &version,

@ -83,11 +83,9 @@ PinBackend* PinBackend::GetInstance() {
std::string PinBackend::ComputeSalt() {
// The salt needs to be base64 encoded because the pref service requires a
// UTF8 string.
std::string salt;
crypto::RandBytes(base::WriteInto(&salt, kSaltByteSize + 1), kSaltByteSize);
salt = base::Base64Encode(salt);
DCHECK(!salt.empty());
return salt;
std::array<uint8_t, kSaltByteSize> bytes;
crypto::RandBytes(bytes);
return base::Base64Encode(bytes);
}
// static

@ -59,9 +59,9 @@ std::optional<std::string> CreateChallengeResponseString(
ChallengeResponse response_pb;
*response_pb.mutable_challenge() = signed_challenge_data;
crypto::RandBytes(base::WriteInto(response_pb.mutable_nonce(),
kChallengeResponseNonceBytesSize + 1),
kChallengeResponseNonceBytesSize);
std::string* nonce = response_pb.mutable_nonce();
nonce->resize(kChallengeResponseNonceBytesSize);
crypto::RandBytes(base::as_writable_byte_span(*nonce));
std::string key;
if (!CryptoUtility::EncryptWithSeed(

@ -122,8 +122,8 @@ bool EncryptWithSeed(const std::string& data,
key = symmetric_key->key();
// Generate initialized vector of size 128 bits.
std::string iv;
crypto::RandBytes(base::WriteInto(&iv, kAesBlockSize + 1), kAesBlockSize);
std::string iv(kAesBlockSize, '\0');
crypto::RandBytes(base::as_writable_byte_span(iv));
crypto::Encryptor encryptor;
if (!encryptor.Init(symmetric_key.get(), crypto::Encryptor::CBC, iv)) {

@ -204,7 +204,7 @@ bool NativeProcessLauncher::LaunchNativeProcess(
}
uint64_t pipe_name_token;
crypto::RandBytes(&pipe_name_token, sizeof(pipe_name_token));
crypto::RandBytes(base::byte_span_from_ref(pipe_name_token));
const std::wstring pipe_name_token_str =
base::ASCIIToWide(base::StringPrintf("%llx", pipe_name_token));
const std::wstring out_pipe_name =

@ -260,7 +260,7 @@ void InstallSigner::GetSignature(SignatureCallback callback) {
}
salt_ = std::string(kSaltBytes, 0);
crypto::RandBytes(std::data(salt_), salt_.size());
crypto::RandBytes(base::as_writable_byte_span(salt_));
std::string hash_base64;
if (!HashWithMachineId(salt_, &hash_base64)) {

@ -160,7 +160,7 @@ DiscoveryNetworkListWinTest::AddConnectionProfile(
std::vector<uint8_t> DiscoveryNetworkListWinTest::GenerateRandomMacAddress()
const {
std::vector<uint8_t> mac_address(6);
base::RandBytes(mac_address.data(), mac_address.size());
base::RandBytes(mac_address);
return mac_address;
}

@ -174,9 +174,9 @@ std::string GetReceiverIdHashToken(PrefService* pref_service) {
std::string token =
pref_service->GetString(prefs::kMediaRouterReceiverIdHashToken);
if (token.empty()) {
crypto::RandBytes(base::WriteInto(&token, kHashTokenSize + 1),
kHashTokenSize);
token = base::Base64Encode(token);
std::array<uint8_t, kHashTokenSize> rand_token;
crypto::RandBytes(rand_token);
token = base::Base64Encode(rand_token);
pref_service->SetString(prefs::kMediaRouterReceiverIdHashToken, token);
}
return token;

@ -9,7 +9,7 @@ namespace {
int64_t CreateRandomId() {
int64_t id;
crypto::RandBytes(&id, sizeof(id));
crypto::RandBytes(base::byte_span_from_ref(id));
return id;
}

@ -251,7 +251,7 @@ bool IsOutOfStorage(const base::FilePath& file_path,
int64_t GeneratePayloadId() {
int64_t payload_id = 0;
crypto::RandBytes(&payload_id, sizeof(payload_id));
crypto::RandBytes(base::byte_span_from_ref(payload_id));
return payload_id;
}

@ -49,7 +49,7 @@ namespace {
int64_t RandInt64() {
int64_t number;
base::RandBytes(&number, sizeof(number));
base::RandBytes(base::byte_span_from_ref(number));
return number;
}

@ -51,15 +51,14 @@ TEST_F(WriteToDiskTest, ASmallVictory) {
// Tests a simple write of data above the chunk threshold.
TEST_F(WriteToDiskTest, LargeData) {
constexpr size_t kBlobSize = 32 * 1024 * 1024 + 13;
std::vector<uint8_t> blob;
blob.resize(kBlobSize);
base::RandBytes(blob.data(), kBlobSize);
std::vector<uint8_t> blob(kBlobSize);
base::RandBytes(blob);
const MemoryRange data = {blob.data(), blob.size()};
const base::FilePath data_path = temp_dir().AppendASCII("data");
ASSERT_PRED2(WriteToDisk, data, data_path.value().c_str());
std::string data_string;
ASSERT_PRED2(base::ReadFileToString, data_path, &data_string);
ASSERT_EQ(::memcmp(data_string.c_str(), blob.data(), kBlobSize), 0);
EXPECT_EQ(base::as_byte_span(data_string), blob);
}
// Tests that the last error code is set when there's a failure.

@ -35,7 +35,7 @@ P2PSocketClient::P2PSocketClient(
random_socket_id_(0),
next_packet_id_(0) {
DCHECK(socket_manager_.is_bound());
crypto::RandBytes(&random_socket_id_, sizeof(random_socket_id_));
crypto::RandBytes(base::byte_span_from_ref(random_socket_id_));
}
P2PSocketClient::~P2PSocketClient() {

@ -39,7 +39,7 @@ void NearbyConnectionImpl::Write(std::vector<uint8_t> bytes) {
NearbyConnectionsManager::PayloadPtr payload =
NearbyConnectionsManager::Payload::New();
crypto::RandBytes(&payload->id, sizeof(payload->id));
crypto::RandBytes(base::byte_span_from_ref(payload->id));
payload->content =
PayloadContent::NewBytes(BytesPayload::New(std::move(bytes)));
nearby_connections_manager_->Send(endpoint_id_, std::move(payload),

@ -43,7 +43,7 @@ uint64_t HmacHash(ReadOnlyHmacKey hmac_key,
}
bool g_hmac_key_overridden = false;
browsing_topics::HmacKey& GetHmacKeyOverrideForTesting() {
static browsing_topics::HmacKey key;
return key;
@ -63,7 +63,7 @@ HmacKey GenerateRandomHmacKey() {
return GetHmacKeyOverrideForTesting();
HmacKey result = {};
base::RandBytes(result.data(), result.size());
base::RandBytes(result);
return result;
}

@ -573,7 +573,7 @@ void JpegClient::PrepareMemory(int32_t bitstream_buffer_id) {
if (exif_size_ > 0) {
auto shm = base::UnsafeSharedMemoryRegion::Create(exif_size_);
auto shm_mapping = shm.Map();
base::RandBytes(shm_mapping.memory(), exif_size_);
base::RandBytes(shm_mapping.GetMemoryAsSpan<uint8_t>());
exif_buffer_ =
media::BitstreamBuffer(bitstream_buffer_id, std::move(shm), exif_size_);
}

@ -127,8 +127,8 @@ class CastNonce {
CastNonce() { GenerateNonce(); }
void GenerateNonce() {
// Create a cryptographically secure nonce.
crypto::RandBytes(base::WriteInto(&nonce_, kNonceSizeInBytes + 1),
kNonceSizeInBytes);
nonce_.resize(kNonceSizeInBytes);
crypto::RandBytes(base::as_writable_byte_span(nonce_));
nonce_generation_time_ = base::Time::Now();
}

@ -40,7 +40,7 @@ class PersistentSystemProfileTest : public testing::Test {
memory_allocator_.reset();
}
void WriteRecord(uint8_t type, const std::string& record) {
void WriteRecord(uint8_t type, std::string_view record) {
persistent_profile_.allocators_[0].Write(
static_cast<PersistentSystemProfile::RecordType>(type), record);
}
@ -75,19 +75,16 @@ TEST_F(PersistentSystemProfileTest, Create) {
TEST_F(PersistentSystemProfileTest, RecordSplitting) {
const size_t kRecordSize = 100 << 10; // 100 KiB
std::vector<char> buffer;
buffer.resize(kRecordSize);
base::RandBytes(&buffer[0], kRecordSize);
std::string buffer(kRecordSize, '\0');
base::RandBytes(base::as_writable_byte_span(buffer));
WriteRecord(42, std::string(&buffer[0], kRecordSize));
WriteRecord(42, buffer);
uint8_t type;
std::string record;
ASSERT_TRUE(ReadRecord(&type, &record));
EXPECT_EQ(42U, type);
ASSERT_EQ(kRecordSize, record.size());
for (size_t i = 0; i < kRecordSize; ++i)
EXPECT_EQ(buffer[i], record[i]);
EXPECT_EQ(buffer, record);
}
TEST_F(PersistentSystemProfileTest, ProfileStorage) {

@ -156,7 +156,7 @@ void ConfigureHttp2Params(const base::CommandLine& command_line,
const uint8_t type = 0x0b + 0x1f * base::RandGenerator(8);
uint8_t flags;
base::RandBytes(&flags, /* output_length = */ sizeof(flags));
base::RandBytes(base::byte_span_from_ref(flags));
const size_t length = base::RandGenerator(7);
// RandBytesAsString() does not support zero length.

@ -55,7 +55,7 @@ int64_t GenerateAndStoreClientId(PrefService* pref_service) {
// non-zero ID to differentiate the case where no ID is set versus the ID is
// 0. We offset by a positive number to return a non-zero client-id.
int64_t number;
base::RandBytes(&number, sizeof(number));
base::RandBytes(base::byte_span_from_ref(number));
client_id = number;
if (client_id == 0) {
// Reassign client_id to a non-zero number.

@ -654,9 +654,10 @@ Status StorageQueue::WriteHeaderAndBlock(
if (total_size > RecordHeader::kSize + data.size()) {
// Fill in with random bytes.
const size_t pad_size = total_size - (RecordHeader::kSize + data.size());
char junk_bytes[FRAME_SIZE];
crypto::RandBytes(junk_bytes, pad_size);
write_status = file->Append(std::string_view(&junk_bytes[0], pad_size));
uint8_t junk_bytes[FRAME_SIZE];
auto padding = base::span(junk_bytes).first(pad_size);
crypto::RandBytes(padding);
write_status = file->Append(base::as_string_view(padding));
if (!write_status.has_value()) {
return Status(error::RESOURCE_EXHAUSTED,
base::StrCat({"Cannot pad file=", file->name(), " status=",

@ -1768,9 +1768,8 @@ std::string TemplateURLService::GetSessionToken() {
base::TimeTicks current_time(base::TimeTicks::Now());
// Renew token if it expired.
if (current_time > token_expiration_time_) {
const size_t kTokenBytes = 12;
std::string raw_data;
base::RandBytes(base::WriteInto(&raw_data, kTokenBytes + 1), kTokenBytes);
std::array<uint8_t, 12> raw_data;
base::RandBytes(raw_data);
base::Base64UrlEncode(raw_data,
base::Base64UrlEncodePolicy::INCLUDE_PADDING,
&current_token_);

@ -20,6 +20,7 @@
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/strings/cstring_view.h"
#include "base/strings/strcat_win.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
@ -55,7 +56,7 @@ enum DeviceType {
// on either floppy or removable volumes. The DRIVE_CDROM type is handled
// as a floppy, as are DRIVE_UNKNOWN and DRIVE_NO_ROOT_DIR, as there are
// reports that some floppy drives don't report as DRIVE_REMOVABLE.
DeviceType GetDeviceType(const std::wstring& mount_point) {
DeviceType GetDeviceType(base::wcstring_view mount_point) {
UINT drive_type = GetDriveType(mount_point.c_str());
if (drive_type == DRIVE_FIXED || drive_type == DRIVE_REMOTE ||
drive_type == DRIVE_RAMDISK) {
@ -66,9 +67,9 @@ DeviceType GetDeviceType(const std::wstring& mount_point) {
// Check device strings of the form "X:" and "\\.\X:"
// For floppy drives, these will return strings like "/Device/Floppy0"
std::wstring device = mount_point;
auto device = std::wstring(mount_point);
if (base::EndsWith(mount_point, L"\\", base::CompareCase::INSENSITIVE_ASCII))
device = mount_point.substr(0, mount_point.length() - 1);
device.resize(device.size() - 1u);
std::wstring device_path;
std::wstring device_path_slash;
DWORD dos_device = QueryDosDevice(

@ -264,7 +264,7 @@ void LoopbackServer::Init() {
std::vector<uint8_t> LoopbackServer::GenerateNewKeystoreKey() const {
std::vector<uint8_t> generated_key(kKeystoreKeyLength);
base::RandBytes(generated_key.data(), generated_key.size());
base::RandBytes(generated_key);
return generated_key;
}

@ -226,8 +226,8 @@ std::string Nigori::GetKeyName() const {
// Enc[Kenc,Kmac](value)
std::string Nigori::Encrypt(const std::string& value) const {
std::string iv;
crypto::RandBytes(base::WriteInto(&iv, kIvSize + 1), kIvSize);
std::array<uint8_t, kIvSize> iv;
crypto::RandBytes(iv);
crypto::Encryptor encryptor;
CHECK(encryptor.Init(keys_.encryption_key.get(), crypto::Encryptor::CBC, iv));
@ -238,13 +238,13 @@ std::string Nigori::Encrypt(const std::string& value) const {
HMAC hmac(HMAC::SHA256);
CHECK(hmac.Init(keys_.mac_key->key()));
std::vector<unsigned char> hash(kHashSize);
CHECK(hmac.Sign(ciphertext, &hash[0], hash.size()));
std::array<uint8_t, kHashSize> hash;
CHECK(hmac.Sign(ciphertext, hash.data(), hash.size()));
std::string output;
output.assign(iv);
output.assign(base::as_string_view(iv));
output.append(ciphertext);
output.append(hash.begin(), hash.end());
output.append(base::as_string_view(hash));
return base::Base64Encode(output);
}
@ -300,10 +300,8 @@ void Nigori::ExportKeys(std::string* user_key,
// static
std::string Nigori::GenerateScryptSalt() {
static const size_t kSaltSizeInBytes = 32;
std::string salt;
salt.resize(kSaltSizeInBytes);
crypto::RandBytes(std::data(salt), salt.size());
std::string salt(32u, '\0');
crypto::RandBytes(base::as_writable_byte_span(salt));
return salt;
}

@ -220,7 +220,7 @@ std::vector<uint8_t> FakeSecurityDomainsServer::RotateTrustedVaultKey(
const std::vector<uint8_t>& last_trusted_vault_key) {
base::AutoLock autolock(lock_);
std::vector<uint8_t> new_trusted_vault_key(kSharedKeyLength);
base::RandBytes(new_trusted_vault_key.data(), kSharedKeyLength);
base::RandBytes(new_trusted_vault_key);
state_.current_epoch++;
state_.trusted_vault_keys.push_back(new_trusted_vault_key);

@ -9429,7 +9429,7 @@ struct ServerLinkValues {
// transaction.
static ServerLinkValues CreateServerLink() {
std::vector<uint8_t> seed(device::cablev2::kQRSeedSize);
base::RandBytes(seed.data(), seed.size());
base::RandBytes(seed);
bssl::UniquePtr<EC_GROUP> p256(
EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1));
@ -9437,7 +9437,7 @@ static ServerLinkValues CreateServerLink() {
EC_KEY_derive_from_secret(p256.get(), seed.data(), seed.size()));
ServerLinkValues ret;
base::RandBytes(ret.secret.data(), ret.secret.size());
base::RandBytes(ret.secret);
CHECK_EQ(ret.peer_identity.size(),
EC_POINT_point2oct(p256.get(), EC_KEY_get0_public_key(ec_key.get()),
POINT_CONVERSION_UNCOMPRESSED,

@ -173,11 +173,10 @@ namespace crypto {
P224EncryptedKeyExchange::P224EncryptedKeyExchange(PeerType peer_type,
std::string_view password)
: state_(kStateInitial), is_server_(peer_type == kPeerTypeServer) {
memset(&x_, 0, sizeof(x_));
memset(&expected_authenticator_, 0, sizeof(expected_authenticator_));
std::ranges::fill(expected_authenticator_, 0u);
// x_ is a random scalar.
RandBytes(x_, sizeof(x_));
RandBytes(x_);
// Calculate |password| hash to get SPAKE password value.
SHA256HashString(std::string(password.data(), password.length()),

@ -12,15 +12,11 @@
namespace crypto {
void RandBytes(void *bytes, size_t length) {
// It's OK to call base::RandBytes(), because it's already strongly random.
// But _other_ code should go through this function to ensure that code which
// needs secure randomness is easily discoverable.
base::RandBytes(bytes, length);
}
void RandBytes(base::span<uint8_t> bytes) {
RandBytes(bytes.data(), bytes.size());
// base::RandBytes() is already strongly random, so this is just an alias for
// it. If base needs a non-strong RNG function in the future, it will get a
// different name.
base::RandBytes(bytes);
}
std::vector<uint8_t> RandBytesAsVector(size_t length) {
@ -30,4 +26,3 @@ std::vector<uint8_t> RandBytesAsVector(size_t length) {
}
} // namespace crypto

@ -14,13 +14,15 @@
namespace crypto {
// Fills the given buffer with `length` random bytes of cryptographically
// secure random numbers.
CRYPTO_EXPORT void RandBytes(void *bytes, size_t length);
// Fills `bytes` with cryptographically-secure random bits.
CRYPTO_EXPORT void RandBytes(base::span<uint8_t> bytes);
// TODO(crbug.com/40284755): Deprecated and will be removed, do not use.
inline void RandBytes(void* bytes, size_t len) {
::crypto::RandBytes(
UNSAFE_BUFFERS(base::span(static_cast<uint8_t*>(bytes), len)));
}
// Returns a vector of `length` bytes filled with cryptographically-secure
// random bits.
CRYPTO_EXPORT std::vector<uint8_t> RandBytesAsVector(size_t length);

@ -14,8 +14,8 @@
// Ensures we don't have all trivial data, i.e. that the data is indeed random.
// Currently, that means the bytes cannot be all the same (e.g. all zeros).
bool IsTrivial(const std::string& bytes) {
for (size_t i = 0; i < bytes.size(); i++) {
bool IsTrivial(base::span<const uint8_t> bytes) {
for (size_t i = 0u; i < bytes.size(); i++) {
if (bytes[i] != bytes[0]) {
return false;
}
@ -24,12 +24,12 @@ bool IsTrivial(const std::string& bytes) {
}
TEST(RandBytes, RandBytes) {
std::string bytes(16, '\0');
crypto::RandBytes(bytes.data(), bytes.size());
std::array<uint8_t, 16> bytes;
crypto::RandBytes(bytes);
EXPECT_FALSE(IsTrivial(bytes));
}
TEST(RandBytes, RandBytesAsVector) {
auto vector = crypto::RandBytesAsVector(16);
EXPECT_FALSE(IsTrivial(std::string(vector.begin(), vector.end())));
std::vector<uint8_t> vector = crypto::RandBytesAsVector(16);
EXPECT_FALSE(IsTrivial(vector));
}

@ -26,7 +26,7 @@ AndroidAccessoryDevice::AndroidAccessoryDevice(
: device_(std::move(device)),
in_endpoint_(in_endpoint),
out_endpoint_(out_endpoint) {
base::RandBytes(id_, sizeof(id_));
base::RandBytes(id_);
}
AndroidAccessoryDevice::~AndroidAccessoryDevice() = default;

@ -4,8 +4,12 @@
#include "device/fido/aoa/android_accessory_discovery.h"
#include <utility>
#include "base/containers/contains.h"
#include "base/containers/extend.h"
#include "base/containers/flat_set.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/metrics/histogram_functions.h"
#include "base/no_destructor.h"
@ -16,10 +20,6 @@
#include "services/device/public/mojom/usb_manager.mojom.h"
#include "services/device/public/mojom/usb_manager_client.mojom.h"
#include <utility>
#include "base/functional/bind.h"
// See https://source.android.com/devices/accessories/aoa for details on the
// protocol used to talk to apps on the phone here.
@ -261,11 +261,11 @@ void AndroidAccessoryDiscovery::OnAccessoryInterfaceClaimed(
}
std::array<uint8_t, kSyncNonceLength> nonce;
base::RandBytes(&nonce[0], kSyncNonceLength);
base::RandBytes(nonce);
std::vector<uint8_t> packet;
packet.push_back(AndroidAccessoryDevice::kCoaoaSync);
packet.insert(packet.end(), nonce.begin(), nonce.end());
base::Extend(packet, nonce);
auto* device_ptr = device.get();
const uint8_t out_endpoint = interface_info.out_endpoint;

@ -379,7 +379,7 @@ std::array<uint8_t, kP256X962Length> PublicKeyOf(const EC_KEY* private_key) {
TEST(CableV2Encoding, Digits) {
uint8_t test_data[24];
base::RandBytes(test_data, sizeof(test_data));
base::RandBytes(test_data);
// |BytesToDigits| and |DigitsToBytes| should round-trip.
for (size_t i = 0; i < sizeof(test_data); i++) {

@ -137,10 +137,10 @@ class FidoDeviceAuthenticatorTest : public testing::Test {
}
AuthenticatorGetAssertionResponse GetAssertionForWrite(
const std::vector<uint8_t>& blob,
base::span<const uint8_t> blob,
std::vector<uint8_t> credential_id = kCredentialId1) {
CtapGetAssertionOptions options;
options.large_blob_write = std::move(blob);
options.large_blob_write.emplace(blob.begin(), blob.end());
std::vector<std::vector<uint8_t>> credential_ids;
credential_ids.push_back(std::move(credential_id));
std::vector<AuthenticatorGetAssertionResponse> responses =
@ -207,14 +207,13 @@ TEST_F(FidoDeviceAuthenticatorTest,
// Test reading and writing a blob that must fit in multiple fragments.
TEST_F(FidoDeviceAuthenticatorTest, TestWriteLargeBlob) {
std::vector<uint8_t> large_blob;
large_blob.resize(2048);
base::RandBytes(large_blob.data(), large_blob.size());
std::array<uint8_t, 2048> large_blob;
base::RandBytes(large_blob);
AuthenticatorGetAssertionResponse write = GetAssertionForWrite(large_blob);
EXPECT_TRUE(write.large_blob_written);
std::vector<AuthenticatorGetAssertionResponse> read = GetAssertionForRead();
EXPECT_EQ(read.at(0).large_blob, large_blob);
EXPECT_EQ(base::span(*read.at(0).large_blob), large_blob);
}
// Test reading and writing a blob using a PinUvAuthToken.
@ -297,7 +296,7 @@ TEST_F(FidoDeviceAuthenticatorTest, TestWriteLargeBlobTooLarge) {
// compressed, so fill it with random data so it doesn't shrink.
std::vector<uint8_t> large_blob;
large_blob.resize(kLargeBlobStorageSize * 2);
base::RandBytes(large_blob.data(), large_blob.size());
base::RandBytes(large_blob);
AuthenticatorGetAssertionResponse write =
GetAssertionForWrite(std::move(large_blob));
EXPECT_FALSE(write.large_blob_written);

@ -508,8 +508,7 @@ void VirtualFidoDevice::State::InjectLargeBlob(RegistrationData* credential,
});
} else {
credential->large_blob_key.emplace();
base::RandBytes(credential->large_blob_key->data(),
credential->large_blob_key->size());
base::RandBytes(*credential->large_blob_key);
}
large_blob_array.emplace_back(
@ -693,7 +692,7 @@ FidoTransportProtocol VirtualFidoDevice::DeviceTransport() const {
// static
std::string VirtualFidoDevice::MakeVirtualFidoDeviceId() {
uint8_t rand_bytes[32];
base::RandBytes(rand_bytes, sizeof(rand_bytes));
base::RandBytes(rand_bytes);
return "VirtualFidoDevice-" + base::HexEncode(rand_bytes);
}

@ -20,6 +20,7 @@
#include "base/bits.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/containers/span.h"
#include "base/debug/alias.h"
#include "base/debug/crash_logging.h"
#include "base/feature_list.h"
@ -64,7 +65,12 @@ std::optional<gin::V8SnapshotFileType> g_snapshot_file_type;
#endif
bool GenerateEntropy(unsigned char* buffer, size_t amount) {
base::RandBytes(buffer, amount);
base::RandBytes(
// SAFETY: This depends on callers providing a valid pointer/size pair.
//
// TODO(crbug.com/338574383): The signature is fixed as it's a callback
// from v8, but maybe v8 can use a span.
UNSAFE_BUFFERS(base::span(buffer, amount)));
return true;
}

@ -32,7 +32,7 @@ void MarkMailboxAsSharedImage(bool is_shared_image, int8_t* name) {
Mailbox GenerateMailbox(bool is_shared_image) {
Mailbox result;
// Generates cryptographically-secure bytes.
base::RandBytes(result.name, sizeof(result.name));
base::RandBytes(base::as_writable_byte_span(result.name));
MarkMailboxAsSharedImage(is_shared_image, result.name);
#if !defined(NDEBUG)
int8_t value = 1;

@ -26,10 +26,10 @@ class MemoryDataSourceTest : public ::testing::Test {
protected:
void Initialize(size_t size) {
data_.assign(size, 0);
base::RandBytes(data_.data(), size);
data_.assign(size, 0u);
base::RandBytes(data_);
memory_data_source_ =
std::make_unique<MemoryDataSource>(data_.data(), size);
std::make_unique<MemoryDataSource>(data_.data(), data_.size());
EXPECT_EQ(size, GetSize());
}

@ -299,7 +299,10 @@ IpczResult IPCZ_API GenerateRandomBytes(size_t num_bytes,
if (!buffer || !num_bytes) {
return IPCZ_RESULT_INVALID_ARGUMENT;
}
base::RandBytes(buffer, num_bytes);
base::RandBytes(
// SAFETY: This requires the caller to provide a valid pointer/size pair.
// The function API is a C API so can't use a span.
UNSAFE_BUFFERS(base::span(static_cast<uint8_t*>(buffer), num_bytes)));
return IPCZ_RESULT_OK;
}

@ -899,7 +899,7 @@ TEST_F(MessageTest, ExtendMessagePayloadLarge) {
// progressively extend the payload to this size.
constexpr size_t kTestMessagePayloadSize = 512 * 1024;
std::vector<uint8_t> test_payload(kTestMessagePayloadSize);
base::RandBytes(test_payload.data(), kTestMessagePayloadSize);
base::RandBytes(test_payload);
size_t current_payload_size = 0;
while (current_payload_size < kTestMessagePayloadSize) {

@ -32,26 +32,15 @@
#include <windows.h>
#endif
#if !BUILDFLAG(IS_NACL)
#include "crypto/random.h"
#endif
namespace mojo {
namespace core {
namespace {
#if BUILDFLAG(IS_NACL)
template <typename T>
void GenerateRandomName(T* out) {
base::RandBytes(out, sizeof(T));
base::RandBytes(base::byte_span_from_ref(*out));
}
#else
template <typename T>
void GenerateRandomName(T* out) {
crypto::RandBytes(out, sizeof(T));
}
#endif
ports::NodeName GetRandomNodeName() {
ports::NodeName name;

@ -17,6 +17,7 @@
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/notreached.h"
#include "base/rand_util.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread_local.h"
#include "build/build_config.h"
@ -25,12 +26,6 @@
#include "mojo/core/ports/port_locker.h"
#include "third_party/abseil-cpp/absl/container/inlined_vector.h"
#if !BUILDFLAG(IS_NACL)
#include "crypto/random.h"
#else
#include "base/rand_util.h"
#endif
namespace mojo {
namespace core {
namespace ports {
@ -58,11 +53,7 @@ class RandomNameGenerator {
PortName GenerateRandomPortName() {
base::AutoLock lock(lock_);
if (cache_index_ == kRandomNameCacheSize) {
#if BUILDFLAG(IS_NACL)
base::RandBytes(cache_, sizeof(PortName) * kRandomNameCacheSize);
#else
crypto::RandBytes(cache_, sizeof(PortName) * kRandomNameCacheSize);
#endif
base::RandBytes(base::as_writable_byte_span(cache_));
cache_index_ = 0;
}
return cache_[cache_index_++];

@ -37,7 +37,7 @@ TEST(BigBufferTest, EmptyBuffer) {
}
TEST(BigBufferTest, SmallDataSize) {
BigBuffer in(std::vector<uint8_t>{1, 2, 3});
BigBuffer in(std::array<uint8_t, 3>{1, 2, 3});
EXPECT_EQ(BigBuffer::StorageType::kBytes, in.storage_type());
BigBuffer out;
@ -49,8 +49,8 @@ TEST(BigBufferTest, SmallDataSize) {
TEST(BigBufferTest, LargeDataSize) {
constexpr size_t kLargeDataSize = BigBuffer::kMaxInlineBytes * 2;
std::vector<uint8_t> data(kLargeDataSize);
base::RandBytes(data.data(), kLargeDataSize);
std::array<uint8_t, kLargeDataSize> data;
base::RandBytes(data);
BigBuffer in(data);
EXPECT_EQ(BigBuffer::StorageType::kSharedMemory, in.storage_type());
@ -62,7 +62,7 @@ TEST(BigBufferTest, LargeDataSize) {
// NOTE: It's not safe to compare to |in| here since serialization will have
// taken ownership of its internal shared buffer handle.
EXPECT_TRUE(BufferEquals(data, out));
EXPECT_TRUE(BufferEquals(base::span<const uint8_t>(data), out));
}
TEST(BigBufferTest, InvalidBuffer) {

@ -32,7 +32,7 @@ TEST(BigStringTest, Long) {
constexpr size_t kLargeStringSize = 1024 * 1024;
std::string in(kLargeStringSize, 0);
base::RandBytes(&in[0], kLargeStringSize);
base::RandBytes(base::as_writable_byte_span(in));
std::string out;
ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::BigString>(in, out));

@ -47,7 +47,7 @@ TEST(BigString16Test, Long) {
constexpr size_t kLargeStringSize = 1024 * 1024;
std::u16string in(kLargeStringSize, 0);
base::RandBytes(&in[0], kLargeStringSize);
base::RandBytes(base::as_writable_byte_span(in));
std::u16string out;
ASSERT_TRUE(mojo::test::SerializeAndDeserialize<mojom::BigString16>(in, out));

@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <memory>
#include <string>
#include <string_view>
@ -142,10 +143,10 @@ class HttpAuthHandlerNtlmPortableTest : public PlatformTest {
return static_cast<HttpAuthHandlerNTLM*>(auth_handler_.get());
}
static void MockRandom(uint8_t* output, size_t n) {
static void MockRandom(base::span<uint8_t> output) {
// This is set to 0xaa because the client challenge for testing in
// [MS-NLMP] Section 4.2.1 is 8 bytes of 0xaa.
memset(output, 0xaa, n);
std::ranges::fill(output, 0xaa);
}
static uint64_t MockGetMSTime() {

@ -26,8 +26,8 @@ uint64_t GetMSTime() {
return base::Time::Now().since_origin().InMicroseconds() * 10;
}
void GenerateRandom(uint8_t* output, size_t n) {
base::RandBytes(output, n);
void GenerateRandom(base::span<uint8_t> output) {
base::RandBytes(output);
}
// static
@ -149,7 +149,7 @@ int HttpAuthNtlmMechanism::GenerateAuthToken(
return ERR_UNEXPECTED;
uint8_t client_challenge[8];
g_generate_random_proc(client_challenge, 8);
g_generate_random_proc(client_challenge);
auto next_token = ntlm_client_.GenerateAuthenticateMessage(
domain, user, credentials->password(), hostname, channel_bindings, spn,

@ -9,6 +9,7 @@
#include <string>
#include "base/containers/span.h"
#include "net/base/auth.h"
#include "net/base/net_export.h"
#include "net/http/http_auth_mechanism.h"
@ -28,8 +29,8 @@ class NET_EXPORT_PRIVATE HttpAuthNtlmMechanism : public HttpAuthMechanism {
// since Jan 1, 1601 (UTC).
using GetMSTimeProc = uint64_t (*)();
// A function that generates n random bytes in the output buffer.
using GenerateRandomProc = void (*)(uint8_t* output, size_t n);
// A function that generates random bytes into the entire output buffer.
using GenerateRandomProc = void (*)(base::span<uint8_t> output);
// A function that returns the local host name. Returns an empty string if
// the local host name is not available.

@ -8,6 +8,7 @@
#include <stdarg.h>
#include <stdint.h>
#include <algorithm>
#include <limits>
#include <memory>
#include <optional>
@ -673,10 +674,10 @@ uint64_t MockGetMSTime() {
// Alternative functions that eliminate randomness and dependency on the local
// host name so that the generated NTLM messages are reproducible.
void MockGenerateRandom(uint8_t* output, size_t n) {
void MockGenerateRandom(base::span<uint8_t> output) {
// This is set to 0xaa because the client challenge for testing in
// [MS-NLMP] Section 4.2.1 is 8 bytes of 0xaa.
memset(output, 0xaa, n);
std::ranges::fill(output, 0xaa);
}
std::string MockGetHostName() {

@ -181,7 +181,7 @@ WebSocketMaskingKey GenerateWebSocketMaskingKey() {
// number generator, which means web application authors should not be able
// to guess the next value of masking key.
WebSocketMaskingKey masking_key;
base::RandBytes(masking_key.key, WebSocketFrameHeader::kMaskingKeyLength);
base::RandBytes(masking_key.key);
return masking_key;
}

@ -18,7 +18,9 @@ namespace ppapi {
namespace {
void GetRandomBytes(char* buffer, uint32_t num_bytes) {
base::RandBytes(buffer, num_bytes);
base::RandBytes(base::as_writable_bytes(
// SAFETY: The caller is required to give a valid pointer and size pair.
UNSAFE_BUFFERS(base::span(buffer, num_bytes))));
}
const PPB_Crypto_Dev crypto_interface = {&GetRandomBytes};

@ -24,7 +24,7 @@ const char kHostSecretAlphabet[] = "0123456789";
// Generates cryptographically strong random number in the range [0, max).
int CryptoRandomInt(int max) {
uint32_t random_int32;
base::RandBytes(&random_int32, sizeof(random_int32));
base::RandBytes(base::byte_span_from_ref(random_int32));
return random_int32 % max;
}

@ -115,9 +115,8 @@ void TokenValidatorImpl::StartValidateRequest(const std::string& token) {
std::string TokenValidatorImpl::CreateScope(const std::string& local_jid,
const std::string& remote_jid) {
std::string nonce_bytes;
crypto::RandBytes(base::WriteInto(&nonce_bytes, kNonceLength + 1),
kNonceLength);
std::array<uint8_t, kNonceLength> nonce_bytes;
crypto::RandBytes(nonce_bytes);
std::string nonce = base::Base64Encode(nonce_bytes);
// Note that because of how FTL signaling IDs are managed, |local_jid| will
// not change between connections to a given host instance. We do expect that

@ -33,7 +33,7 @@ bool GetMachineId(std::string* machine_id) {
// hex character for 45 characters.
unsigned char bytes[23];
std::string str_bytes;
base::RandBytes(bytes, sizeof(bytes));
base::RandBytes(bytes);
rlz_lib::BytesToString(bytes, sizeof(bytes), &str_bytes);
str_bytes.resize(45);
machine_id->clear();

@ -106,7 +106,7 @@ TEST(Convolver, Halve) {
output.resize(dest_byte_count);
// First fill the array with a bunch of random data.
base::RandBytes(input.data(), input.size());
base::RandBytes(input);
// Compute the filters.
ConvolutionFilter1D filter_x, filter_y;

@ -507,11 +507,11 @@ bool IsolatedContext::UnregisterFileSystem(const std::string& filesystem_id) {
std::string IsolatedContext::GetNewFileSystemId() const {
// Returns an arbitrary random string which must be unique in the map.
lock_.AssertAcquired();
uint32_t random_data[4];
uint8_t random_data[16];
std::string id;
do {
base::RandBytes(random_data, sizeof(random_data));
id = base::HexEncode(random_data, sizeof(random_data));
base::RandBytes(random_data);
id = base::HexEncode(random_data);
} while (base::Contains(instance_map_, id));
return id;
}

@ -46,7 +46,7 @@ bool ShouldPadResponseType(network::mojom::FetchResponseType type) {
int64_t ComputeRandomResponsePadding() {
uint64_t raw_random = 0;
crypto::RandBytes(&raw_random, sizeof(uint64_t));
crypto::RandBytes(base::byte_span_from_ref(raw_random));
return raw_random % kPaddingRange;
}

@ -1039,7 +1039,7 @@ void ThreadDebuggerCommonImpl::cancelTimer(void* data) {
int64_t ThreadDebuggerCommonImpl::generateUniqueId() {
int64_t result;
base::RandBytes(&result, sizeof result);
base::RandBytes(base::byte_span_from_ref(result));
return result;
}

@ -73,7 +73,7 @@ NotShared<DOMArrayBufferView> Crypto::getRandomValues(
array->byteLength()));
return NotShared<DOMArrayBufferView>(nullptr);
}
crypto::RandBytes(array->BaseAddress(), array->byteLength());
crypto::RandBytes(array->ByteSpan());
return array;
}

@ -284,7 +284,7 @@ void CanvasCaptureHandler::AddVideoCapturerSourceToVideoTrack(
std::unique_ptr<VideoCapturerSource> source,
MediaStreamComponent** component) {
uint8_t track_id_bytes[64];
base::RandBytes(track_id_bytes, sizeof(track_id_bytes));
base::RandBytes(track_id_bytes);
String track_id = Base64Encode(track_id_bytes);
media::VideoCaptureFormats preferred_formats = source->GetPreferredFormats();
auto stream_video_source = std::make_unique<MediaStreamVideoCapturerSource>(

@ -58,7 +58,7 @@ String MakeComplexString(size_t size) {
Vector<char> data(size, 'a');
// This string should not be compressed too much, but also should not
// be compressed failed. So make only some parts of this random.
base::RandBytes(data.data(), data.size() / 10);
base::RandBytes(base::as_writable_byte_span(data).first(size / 10u));
return String(data.data(), data.size()).ReleaseImpl();
}
@ -236,7 +236,7 @@ TEST_P(ParkableStringTest, DontCompressRandomString) {
// gzip's header). Mersenne-Twister implementation is specified, making the
// test deterministic.
Vector<unsigned char> data(kSizeKb * 1000);
base::RandBytes(data.data(), data.size());
base::RandBytes(data);
ParkableString parkable(String(data.data(), data.size()).ReleaseImpl());
EXPECT_TRUE(
@ -806,7 +806,7 @@ TEST_P(ParkableStringTest, SynchronousCompression) {
TEST_P(ParkableStringTest, CompressionFailed) {
const size_t kSize = 20000;
Vector<char> data(kSize);
base::RandBytes(data.data(), data.size());
base::RandBytes(base::as_writable_byte_span(data));
ParkableString parkable(String(data.data(), data.size()).ReleaseImpl());
WaitForDelayedParking();
EXPECT_EQ(ParkableStringImpl::Age::kOld, parkable.Impl()->age_for_testing());

@ -55,7 +55,7 @@ TEST(BigStringMojomTraitsTest, BigString_Short) {
TEST(BigStringMojomTraitsTest, BigString_Long) {
WTF::Vector<char> random_latin1_string(1024 * 1024);
base::RandBytes(random_latin1_string.data(), random_latin1_string.size());
base::RandBytes(base::as_writable_byte_span(random_latin1_string));
String str(random_latin1_string.data(), random_latin1_string.size());
String output;

@ -77,7 +77,7 @@ TEST(String16MojomTraitsTest, BigString16_Short) {
TEST(String16MojomTraitsTest, BigString16_Long) {
WTF::Vector<char> random_latin1_string(1024 * 1024);
base::RandBytes(random_latin1_string.data(), random_latin1_string.size());
base::RandBytes(base::as_writable_byte_span(random_latin1_string));
String str(random_latin1_string.data(), random_latin1_string.size());
String output;

@ -147,7 +147,7 @@ Vector<char> FormDataEncoder::GenerateUniqueBoundaryString() {
// Append 16 random 7bit ascii AlphaNumeric characters.
char random_bytes[16];
base::RandBytes(random_bytes, sizeof(random_bytes));
base::RandBytes(base::as_writable_byte_span(random_bytes));
for (char& c : random_bytes)
c = kAlphaNumericEncodingMap[c & 0x3F];
boundary.Append(random_bytes, sizeof(random_bytes));

@ -40,7 +40,7 @@ P2PSocketClientImpl::P2PSocketClientImpl(bool batch_packets)
state_(kStateUninitialized),
random_socket_id_(0),
next_packet_id_(0) {
crypto::RandBytes(&random_socket_id_, sizeof(random_socket_id_));
crypto::RandBytes(base::byte_span_from_ref(random_socket_id_));
}
P2PSocketClientImpl::~P2PSocketClientImpl() {

@ -159,6 +159,14 @@ _CONFIG = [
'base::sequence_manager::TaskTimeObserver',
'base::span',
'base::Span(Reader|Writer)',
'base::as_byte_span',
'base::as_writable_byte_span',
'base::as_bytes',
'base::as_writable_bytes',
'base::as_chars',
'base::as_writable_chars',
'base::as_string_view',
'base::(byte_)?span_from_ref',
'logging::GetVlogLevel',
'logging::SetLogItems',

@ -63,27 +63,27 @@ int RandInt(int min, int max) {
return GetRandom()(max - min + 1) + min;
}
void RandBytes(void* output, size_t output_len) {
uint8_t* out = static_cast<uint8_t*>(output);
for (size_t i = 0; i < output_len / sizeof(size_t); i++) {
void RandBytes(base::span<uint8_t> output) {
size_t offset = 0u;
for (size_t i = 0u; i < output.size() / sizeof(size_t); i++) {
size_t rand_num = GetRandom()();
for (size_t j = 0; j < sizeof(size_t); j++) {
*out = *reinterpret_cast<uint8_t*>(&rand_num);
out++;
for (size_t j = 0u; j < sizeof(size_t); j++) {
output[offset] = *reinterpret_cast<uint8_t*>(&rand_num);
offset++;
rand_num >>= 8;
}
}
size_t rand_num = GetRandom()();
for (size_t j = 0; j < output_len % sizeof(size_t); j++) {
*out = *reinterpret_cast<uint8_t*>(&rand_num);
out++;
for (size_t j = 0u; j < output.size() % sizeof(size_t); j++) {
output[offset] = *reinterpret_cast<uint8_t*>(&rand_num);
offset++;
rand_num >>= 8;
}
}
std::string RandBytesAsString(size_t length) {
std::string result;
RandBytes(base::WriteInto(&result, length + 1), length);
std::string result(length, '\0');
RandBytes(base::as_writable_byte_span(result));
return result;
}