0

Switch SHA256HashValue to a std::array.

It used to contain a fixed-length C-style array. Using a std::array is
safer.

Bug: 390223051
Change-Id: I33b1b207b1fde986a185c9d53fda3a7f61a05196
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/6382619
Reviewed-by: Nico Weber <thakis@chromium.org>
Owners-Override: Nico Weber <thakis@chromium.org>
Commit-Queue: mmenke <mmenke@chromium.org>
Reviewed-by: Matt Mueller <mattm@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1437923}
This commit is contained in:
Matt Menke
2025-03-25 21:04:21 -07:00
committed by Chromium LUCI CQ
parent de17170f9e
commit 3019accff6
58 changed files with 126 additions and 174 deletions
chrome/browser
components
content
ios/web/session
net
services
third_party/blink

@@ -12,10 +12,10 @@
#include "base/containers/flat_map.h" #include "base/containers/flat_map.h"
#include "base/synchronization/lock.h" #include "base/synchronization/lock.h"
#include "chromeos/components/certificate_provider/certificate_info.h" #include "chromeos/components/certificate_provider/certificate_info.h"
#include "net/base/hash_value.h"
namespace net { namespace net {
class X509Certificate; class X509Certificate;
struct SHA256HashValue;
} // namespace net } // namespace net
namespace chromeos { namespace chromeos {

@@ -279,7 +279,7 @@ net::X509Certificate* FindCertificateFromCertificateList(
std::string_view sha256_hex_hash, std::string_view sha256_hex_hash,
const net::CertificateList& certs) { const net::CertificateList& certs) {
net::SHA256HashValue hash; net::SHA256HashValue hash;
if (!base::HexStringToSpan(sha256_hex_hash, hash.data)) { if (!base::HexStringToSpan(sha256_hex_hash, hash)) {
return nullptr; return nullptr;
} }
@@ -414,7 +414,7 @@ class WritableCertLoader : public CertificateManagerPageHandler::CertSource {
} }
net::SHA256HashValue hash; net::SHA256HashValue hash;
if (!base::HexStringToSpan(sha256_hex_hash, hash.data)) { if (!base::HexStringToSpan(sha256_hex_hash, hash)) {
return nullptr; return nullptr;
} }

@@ -71,7 +71,7 @@ bool SlotContainsCertWithHash(PK11SlotInfo* slot, std::string_view hash_hex) {
return false; return false;
} }
net::SHA256HashValue hash; net::SHA256HashValue hash;
if (!base::HexStringToSpan(hash_hex, hash.data)) { if (!base::HexStringToSpan(hash_hex, hash)) {
return false; return false;
} }
for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list); for (CERTCertListNode* node = CERT_LIST_HEAD(cert_list);

@@ -139,13 +139,11 @@ TEST_F(UserCertSourcesUnitTest, TestGetCertificateInfos) {
EXPECT_EQ(infos[0]->sha256hash_hex, EXPECT_EQ(infos[0]->sha256hash_hex,
base::ToLowerASCII( base::ToLowerASCII(
base::HexEncode(net::X509Certificate::CalculateFingerprint256( base::HexEncode(net::X509Certificate::CalculateFingerprint256(
test_cert_1->cert_buffer()) test_cert_1->cert_buffer()))));
.data)));
EXPECT_EQ(infos[1]->sha256hash_hex, EXPECT_EQ(infos[1]->sha256hash_hex,
base::ToLowerASCII( base::ToLowerASCII(
base::HexEncode(net::X509Certificate::CalculateFingerprint256( base::HexEncode(net::X509Certificate::CalculateFingerprint256(
test_cert_2->cert_buffer()) test_cert_2->cert_buffer()))));
.data)));
} }
TEST_F(UserCertSourcesUnitTest, TestImportCertificate) { TEST_F(UserCertSourcesUnitTest, TestImportCertificate) {
@@ -332,8 +330,7 @@ TEST_F(UserCertSourcesUnitTest, TestDeleteCertificate) {
source.DeleteCertificate("", source.DeleteCertificate("",
base::ToLowerASCII(base::HexEncode( base::ToLowerASCII(base::HexEncode(
net::X509Certificate::CalculateFingerprint256( net::X509Certificate::CalculateFingerprint256(
test_cert_1->cert_buffer()) test_cert_1->cert_buffer()))),
.data)),
delete_future.GetCallback()); delete_future.GetCallback());
certificate_manager_v2::mojom::ActionResultPtr delete_result = certificate_manager_v2::mojom::ActionResultPtr delete_result =
delete_future.Take(); delete_future.Take();
@@ -346,8 +343,7 @@ TEST_F(UserCertSourcesUnitTest, TestDeleteCertificate) {
EXPECT_EQ(remaining_certs[0].sha256hash_hex, EXPECT_EQ(remaining_certs[0].sha256hash_hex,
base::ToLowerASCII( base::ToLowerASCII(
base::HexEncode(net::X509Certificate::CalculateFingerprint256( base::HexEncode(net::X509Certificate::CalculateFingerprint256(
test_cert_2->cert_buffer()) test_cert_2->cert_buffer()))));
.data)));
EXPECT_TRUE(fake_page->metadata_update_called()); EXPECT_TRUE(fake_page->metadata_update_called());
} }
@@ -380,8 +376,7 @@ TEST_F(UserCertSourcesUnitTest, TestDeleteCertificateConfirmationRejected) {
source.DeleteCertificate("", source.DeleteCertificate("",
base::ToLowerASCII(base::HexEncode( base::ToLowerASCII(base::HexEncode(
net::X509Certificate::CalculateFingerprint256( net::X509Certificate::CalculateFingerprint256(
test_cert_1->cert_buffer()) test_cert_1->cert_buffer()))),
.data)),
delete_future.GetCallback()); delete_future.GetCallback());
certificate_manager_v2::mojom::ActionResultPtr delete_result = certificate_manager_v2::mojom::ActionResultPtr delete_result =
delete_future.Take(); delete_future.Take();
@@ -425,8 +420,7 @@ TEST_F(UserCertSourcesUnitTest, TestDeleteCertificateNotAllowedByPref) {
source.DeleteCertificate("", source.DeleteCertificate("",
base::ToLowerASCII(base::HexEncode( base::ToLowerASCII(base::HexEncode(
net::X509Certificate::CalculateFingerprint256( net::X509Certificate::CalculateFingerprint256(
test_cert_1->cert_buffer()) test_cert_1->cert_buffer()))),
.data)),
delete_future.GetCallback()); delete_future.GetCallback());
certificate_manager_v2::mojom::ActionResultPtr delete_result = certificate_manager_v2::mojom::ActionResultPtr delete_result =
delete_future.Take(); delete_future.Take();

@@ -159,7 +159,7 @@ connectors_internals::mojom::CertificateMetadataPtr ConvertCertificate(
base::ToLowerASCII(base::HexEncode(certificate->serial_number().data(), base::ToLowerASCII(base::HexEncode(certificate->serial_number().data(),
certificate->serial_number().size())), certificate->serial_number().size())),
base::ToLowerASCII( base::ToLowerASCII(
base::HexEncode(certificate->CalculateChainFingerprint256().data)), base::HexEncode(certificate->CalculateChainFingerprint256())),
base::UnlocalizedTimeFormatWithPattern(certificate->valid_start(), base::UnlocalizedTimeFormatWithPattern(certificate->valid_start(),
"MMM d, yyyy"), "MMM d, yyyy"),
base::UnlocalizedTimeFormatWithPattern(certificate->valid_expiry(), base::UnlocalizedTimeFormatWithPattern(certificate->valid_expiry(),

@@ -518,8 +518,7 @@ void NetInternalsMessageHandler::OnGetSharedDictionaryInfoDone(
dict.Set("expiration", base::NumberToString(item->expiration.InSeconds())); dict.Set("expiration", base::NumberToString(item->expiration.InSeconds()));
dict.Set("last_used_time", base::TimeFormatHTTP(item->last_used_time)); dict.Set("last_used_time", base::TimeFormatHTTP(item->last_used_time));
dict.Set("size", base::NumberToString(item->size)); dict.Set("size", base::NumberToString(item->size));
dict.Set("hash", base::ToLowerASCII(base::HexEncode( dict.Set("hash", base::ToLowerASCII(base::HexEncode(item->hash)));
item->hash.data, sizeof(item->hash.data))));
dict_list.Append(std::move(dict)); dict_list.Append(std::move(dict));
} }
AllowJavascript(); AllowJavascript();

@@ -411,7 +411,7 @@ void NetInternalsTest::MessageHandler::RgisterTestSharedDictionary(
CHECK(dictionary_json_string); CHECK(dictionary_json_string);
base::Value::Dict dict = base::test::ParseJsonDict(*dictionary_json_string); base::Value::Dict dict = base::test::ParseJsonDict(*dictionary_json_string);
net::SHA256HashValue hash_value; net::SHA256HashValue hash_value;
base::HexStringToSpan(*dict.FindString("hash"), hash_value.data); base::HexStringToSpan(*dict.FindString("hash"), hash_value);
const std::string* id_string = dict.FindString("id"); const std::string* id_string = dict.FindString("id");
network_context_for_testing_.RegisterTestSharedDictionary( network_context_for_testing_.RegisterTestSharedDictionary(
net::SharedDictionaryIsolationKey( net::SharedDictionaryIsolationKey(

@@ -17,13 +17,13 @@ net::SHA256HashValue ByteArrayToSHA256(
const base::android::JavaRef<jbyteArray>& jdictionary_sha256_hash) { const base::android::JavaRef<jbyteArray>& jdictionary_sha256_hash) {
const auto dictionary_sha256_hash_size = const auto dictionary_sha256_hash_size =
base::android::SafeGetArrayLength(env, jdictionary_sha256_hash); base::android::SafeGetArrayLength(env, jdictionary_sha256_hash);
CHECK_EQ(dictionary_sha256_hash_size, sizeof(net::SHA256HashValue::data)); CHECK_EQ(dictionary_sha256_hash_size, sizeof(net::SHA256HashValue));
net::SHA256HashValue dictionary_sha256_hash; net::SHA256HashValue dictionary_sha256_hash;
void* const bytes = env->GetPrimitiveArrayCritical( void* const bytes = env->GetPrimitiveArrayCritical(
jdictionary_sha256_hash.obj(), /*isCopy=*/nullptr); jdictionary_sha256_hash.obj(), /*isCopy=*/nullptr);
CHECK(bytes); CHECK(bytes);
UNSAFE_TODO( UNSAFE_TODO(memcpy(dictionary_sha256_hash.data(), bytes,
memcpy(&dictionary_sha256_hash.data, bytes, dictionary_sha256_hash_size)); dictionary_sha256_hash_size));
env->ReleasePrimitiveArrayCritical(jdictionary_sha256_hash.obj(), bytes, env->ReleasePrimitiveArrayCritical(jdictionary_sha256_hash.obj(), bytes,
JNI_ABORT); JNI_ABORT);
return dictionary_sha256_hash; return dictionary_sha256_hash;

@@ -167,7 +167,7 @@ std::string GetKey(const net::X509Certificate& cert, int error) {
// Since a security decision will be made based on the fingerprint, Chrome // Since a security decision will be made based on the fingerprint, Chrome
// should use the SHA-256 fingerprint for the certificate. // should use the SHA-256 fingerprint for the certificate.
net::SHA256HashValue fingerprint = cert.CalculateChainFingerprint256(); net::SHA256HashValue fingerprint = cert.CalculateChainFingerprint256();
std::string base64_fingerprint = base::Base64Encode(fingerprint.data); std::string base64_fingerprint = base::Base64Encode(fingerprint);
return base::NumberToString(error) + base64_fingerprint; return base::NumberToString(error) + base64_fingerprint;
} }

@@ -2865,7 +2865,7 @@ void NetworkHandler::OnSignedExchangeReceived(
.SetExpires(sig.expires) .SetExpires(sig.expires)
.Build(); .Build();
if (sig.cert_sha256) { if (sig.cert_sha256) {
signature->SetCertSha256(base::HexEncode(sig.cert_sha256->data)); signature->SetCertSha256(base::HexEncode(*sig.cert_sha256));
} }
if (certificate) { if (certificate) {
auto encoded_certificates = std::make_unique<protocol::Array<String>>(); auto encoded_certificates = std::make_unique<protocol::Array<String>>();

@@ -337,10 +337,10 @@ bool ExtractSHA256HashValueFromString(std::string_view value,
const std::string_view base64_str = value.substr(7); const std::string_view base64_str = value.substr(7);
std::string decoded; std::string decoded;
if (!base::Base64Decode(base64_str, &decoded) || if (!base::Base64Decode(base64_str, &decoded) ||
decoded.size() != sizeof(out->data)) { decoded.size() != out->size()) {
return false; return false;
} }
memcpy(out->data, decoded.data(), sizeof(out->data)); memcpy(out->data(), decoded.data(), out->size());
return true; return true;
} }

@@ -7,14 +7,11 @@
#include "base/time/time.h" #include "base/time/time.h"
#include "content/common/content_export.h" #include "content/common/content_export.h"
#include "net/base/hash_value.h"
#include "services/network/public/cpp/url_loader_completion_status.h" #include "services/network/public/cpp/url_loader_completion_status.h"
#include "services/network/public/mojom/url_response_head.mojom.h" #include "services/network/public/mojom/url_response_head.mojom.h"
#include "url/gurl.h" #include "url/gurl.h"
namespace net {
struct SHA256HashValue;
} // namespace net
namespace storage { namespace storage {
class BlobDataHandle; class BlobDataHandle;
} // namespace storage } // namespace storage

@@ -109,7 +109,8 @@ SignedExchangeSignatureHeaderField::ParseSignature(
return std::nullopt; return std::nullopt;
} }
net::SHA256HashValue cert_sha256; net::SHA256HashValue cert_sha256;
memcpy(&cert_sha256.data, cert_sha256_string.data(), crypto::kSHA256Length); memcpy(cert_sha256.data(), cert_sha256_string.data(),
crypto::kSHA256Length);
sig.cert_sha256 = std::move(cert_sha256); sig.cert_sha256 = std::move(cert_sha256);
// TODO(crbug.com/40565993): Support ed25519key. // TODO(crbug.com/40565993): Support ed25519key.

@@ -154,8 +154,7 @@ std::vector<uint8_t> GenerateSignedMessage(
// format. // format.
message.push_back(32); message.push_back(32);
const auto& cert_sha256 = envelope.signature().cert_sha256.value(); const auto& cert_sha256 = envelope.signature().cert_sha256.value();
message.insert(message.end(), std::begin(cert_sha256.data), message.insert(message.end(), cert_sha256.begin(), cert_sha256.end());
std::end(cert_sha256.data));
// Step 5.5. "The 8-byte big-endian encoding of the length in bytes of // Step 5.5. "The 8-byte big-endian encoding of the length in bytes of
// validity-url, followed by the bytes of validity-url." [spec text] // validity-url, followed by the bytes of validity-url." [spec text]

@@ -189,7 +189,7 @@ class SignedExchangeSignatureVerifierTest
SignedExchangeEnvelope badsigsha256_envelope(envelope); SignedExchangeEnvelope badsigsha256_envelope(envelope);
SignedExchangeSignatureHeaderField::Signature badsigsha256 = SignedExchangeSignatureHeaderField::Signature badsigsha256 =
envelope.signature(); envelope.signature();
badsigsha256.cert_sha256->data[0]++; (*badsigsha256.cert_sha256)[0]++;
badsigsha256_envelope.SetSignatureForTesting(badsigsha256); badsigsha256_envelope.SetSignatureForTesting(badsigsha256);
EXPECT_EQ( EXPECT_EQ(
SignedExchangeSignatureVerifier::Result::kErrCertificateSHA256Mismatch, SignedExchangeSignatureVerifier::Result::kErrCertificateSHA256Mismatch,

@@ -7,16 +7,14 @@
#include <string_view> #include <string_view>
#include "base/base64.h" #include "base/base64.h"
#include "base/strings/strcat.h"
namespace content { namespace content {
namespace signed_exchange_utils { namespace signed_exchange_utils {
std::string CreateHeaderIntegrityHashString( std::string CreateHeaderIntegrityHashString(
const net::SHA256HashValue& header_integrity) { const net::SHA256HashValue& header_integrity) {
std::string header_integrity_base64 = base::Base64Encode( return base::StrCat({"sha256-", base::Base64Encode(header_integrity)});
std::string_view(reinterpret_cast<const char*>(header_integrity.data),
sizeof(header_integrity.data)));
return std::string("sha256-") + header_integrity_base64;
} }
} // namespace signed_exchange_utils } // namespace signed_exchange_utils

@@ -9,6 +9,7 @@
#include <string_view> #include <string_view>
#include <tuple> #include <tuple>
#include "base/containers/span.h"
#include "net/base/hash_value.h" #include "net/base/hash_value.h"
#include "net/cert/x509_certificate.h" #include "net/cert/x509_certificate.h"
@@ -28,8 +29,7 @@ struct Hasher<T*> : Hasher<const T*> {};
template <> template <>
struct Hasher<net::SHA256HashValue> { struct Hasher<net::SHA256HashValue> {
size_t operator()(const net::SHA256HashValue& value) const { size_t operator()(const net::SHA256HashValue& value) const {
const std::string_view value_string_piece( const std::string_view value_string_piece = base::as_string_view(value);
reinterpret_cast<const char*>(&value.data[0]), sizeof(value.data));
return Hasher<std::string_view>{}(value_string_piece); return Hasher<std::string_view>{}(value_string_piece);
} }
}; };

@@ -2,11 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
#include "net/base/hash_value.h" #include "net/base/hash_value.h"
#include <stdlib.h> #include <stdlib.h>
@@ -35,12 +30,12 @@ constexpr std::string_view kSha256Slash = "sha256/";
struct SHA256ToHashValueComparator { struct SHA256ToHashValueComparator {
bool operator()(const SHA256HashValue& lhs, const HashValue& rhs) const { bool operator()(const SHA256HashValue& lhs, const HashValue& rhs) const {
DCHECK_EQ(HASH_VALUE_SHA256, rhs.tag()); DCHECK_EQ(HASH_VALUE_SHA256, rhs.tag());
return memcmp(lhs.data, rhs.data(), rhs.size()) < 0; return lhs < rhs.span();
} }
bool operator()(const HashValue& lhs, const SHA256HashValue& rhs) const { bool operator()(const HashValue& lhs, const SHA256HashValue& rhs) const {
DCHECK_EQ(HASH_VALUE_SHA256, lhs.tag()); DCHECK_EQ(HASH_VALUE_SHA256, lhs.tag());
return memcmp(lhs.data(), rhs.data, lhs.size()) < 0; return lhs.span() < rhs;
} }
}; };
@@ -81,20 +76,33 @@ std::string HashValue::ToString() const {
size_t HashValue::size() const { size_t HashValue::size() const {
switch (tag_) { switch (tag_) {
case HASH_VALUE_SHA256: case HASH_VALUE_SHA256:
return sizeof(fingerprint.sha256.data); return sizeof(fingerprint.sha256);
} }
NOTREACHED(); NOTREACHED();
} }
unsigned char* HashValue::data() { unsigned char* HashValue::data() {
return const_cast<unsigned char*>(const_cast<const HashValue*>(this)->data()); return span().data();
} }
const unsigned char* HashValue::data() const { const unsigned char* HashValue::data() const {
return span().data();
}
base::span<uint8_t> HashValue::span() {
switch (tag_) { switch (tag_) {
case HASH_VALUE_SHA256: case HASH_VALUE_SHA256:
return fingerprint.sha256.data; return fingerprint.sha256;
}
NOTREACHED();
}
base::span<const uint8_t> HashValue::span() const {
switch (tag_) {
case HASH_VALUE_SHA256:
return fingerprint.sha256;
} }
NOTREACHED(); NOTREACHED();

@@ -2,11 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. // found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
#ifndef NET_BASE_HASH_VALUE_H_ #ifndef NET_BASE_HASH_VALUE_H_
#define NET_BASE_HASH_VALUE_H_ #define NET_BASE_HASH_VALUE_H_
@@ -14,6 +9,7 @@
#include <stdint.h> #include <stdint.h>
#include <string.h> #include <string.h>
#include <array>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <vector> #include <vector>
@@ -26,33 +22,7 @@
namespace net { namespace net {
struct NET_EXPORT SHA256HashValue { using SHA256HashValue = std::array<uint8_t, 32>;
unsigned char data[32];
};
inline bool operator==(const SHA256HashValue& lhs, const SHA256HashValue& rhs) {
return memcmp(lhs.data, rhs.data, sizeof(lhs.data)) == 0;
}
inline bool operator!=(const SHA256HashValue& lhs, const SHA256HashValue& rhs) {
return memcmp(lhs.data, rhs.data, sizeof(lhs.data)) != 0;
}
inline bool operator<(const SHA256HashValue& lhs, const SHA256HashValue& rhs) {
return memcmp(lhs.data, rhs.data, sizeof(lhs.data)) < 0;
}
inline bool operator>(const SHA256HashValue& lhs, const SHA256HashValue& rhs) {
return memcmp(lhs.data, rhs.data, sizeof(lhs.data)) > 0;
}
inline bool operator<=(const SHA256HashValue& lhs, const SHA256HashValue& rhs) {
return memcmp(lhs.data, rhs.data, sizeof(lhs.data)) <= 0;
}
inline bool operator>=(const SHA256HashValue& lhs, const SHA256HashValue& rhs) {
return memcmp(lhs.data, rhs.data, sizeof(lhs.data)) >= 0;
}
enum HashValueTag { enum HashValueTag {
HASH_VALUE_SHA256, HASH_VALUE_SHA256,
@@ -89,6 +59,9 @@ class NET_EXPORT HashValue {
unsigned char* data(); unsigned char* data();
const unsigned char* data() const; const unsigned char* data() const;
base::span<uint8_t> span();
base::span<const uint8_t> span() const;
// Iterate memory as bytes up to the end of its logical size. // Iterate memory as bytes up to the end of its logical size.
iterator begin() { iterator begin() {
// SAFETY: `data()` points to at least `size()` contiguous elements, so this // SAFETY: `data()` points to at least `size()` contiguous elements, so this

@@ -772,8 +772,9 @@ bool CertVerifyProc::HasNameConstraintsViolation(
for (const auto& hash : public_key_hashes) { for (const auto& hash : public_key_hashes) {
if (hash.tag() != HASH_VALUE_SHA256) if (hash.tag() != HASH_VALUE_SHA256)
continue; continue;
if (memcmp(hash.data(), limit.public_key_hash.data, hash.size()) != 0) if (hash.span() != limit.public_key_hash) {
continue; continue;
}
if (dns_names.empty() && ip_addrs.empty()) { if (dns_names.empty() && ip_addrs.empty()) {
std::vector<std::string> names; std::vector<std::string> names;
names.push_back(common_name); names.push_back(common_name);

@@ -17,6 +17,7 @@
#include "base/time/time.h" #include "base/time/time.h"
#include "base/values.h" #include "base/values.h"
#include "components/network_time/time_tracker/time_tracker.h" #include "components/network_time/time_tracker/time_tracker.h"
#include "crypto/hash.h"
#include "crypto/sha2.h" #include "crypto/sha2.h"
#include "net/base/features.h" #include "net/base/features.h"
#include "net/base/ip_address.h" #include "net/base/ip_address.h"
@@ -689,10 +690,7 @@ class PathBuilderDelegateImpl : public bssl::SimplePathBuilderDelegate {
return false; return false;
} }
SHA256HashValue root_fingerprint; SHA256HashValue root_fingerprint = crypto::hash::Sha256(root->der_cert());
crypto::SHA256HashString(root->der_cert().AsStringView(),
root_fingerprint.data,
sizeof(root_fingerprint.data));
for (const bssl::der::Input& oid : path->user_constrained_policy_set) { for (const bssl::der::Input& oid : path->user_constrained_policy_set) {
if (ev_metadata_->HasEVPolicyOID(root_fingerprint, oid)) { if (ev_metadata_->HasEVPolicyOID(root_fingerprint, oid)) {

@@ -25,6 +25,7 @@
#include "base/threading/thread.h" #include "base/threading/thread.h"
#include "base/time/time.h" #include "base/time/time.h"
#include "build/build_config.h" #include "build/build_config.h"
#include "crypto/hash.h"
#include "crypto/sha2.h" #include "crypto/sha2.h"
#include "net/base/cronet_buildflags.h" #include "net/base/cronet_buildflags.h"
#include "net/base/net_errors.h" #include "net/base/net_errors.h"
@@ -519,8 +520,7 @@ TEST_P(CertVerifyProcInternalTest, EVVerificationMultipleOID) {
std::string_view spki; std::string_view spki;
ASSERT_TRUE(asn1::ExtractSPKIFromDERCert( ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(
x509_util::CryptoBufferAsStringPiece(root->GetCertBuffer()), &spki)); x509_util::CryptoBufferAsStringPiece(root->GetCertBuffer()), &spki));
SHA256HashValue spki_sha256; SHA256HashValue spki_sha256 = crypto::hash::Sha256(base::as_byte_span(spki));
crypto::SHA256HashString(spki, spki_sha256.data, sizeof(spki_sha256.data));
SetUpCertVerifyProc(CRLSet::ForTesting(false, &spki_sha256, "", "", {})); SetUpCertVerifyProc(CRLSet::ForTesting(false, &spki_sha256, "", "", {}));
// Consider the root of the test chain a valid EV root for the test policy. // Consider the root of the test chain a valid EV root for the test policy.

@@ -434,8 +434,7 @@ scoped_refptr<CRLSet> CRLSet::ForTesting(
crl_set->not_after_ = 1; crl_set->not_after_ = 1;
if (issuer_spki) { if (issuer_spki) {
std::string spki(reinterpret_cast<const char*>(issuer_spki->data), std::string spki(base::as_string_view(*issuer_spki));
sizeof(issuer_spki->data));
std::vector<std::string> serials; std::vector<std::string> serials;
if (!serial_number.empty()) { if (!serial_number.empty()) {
serials.push_back(std::string(serial_number)); serials.push_back(std::string(serial_number));

@@ -12,6 +12,7 @@
#include <string_view> #include <string_view>
#include "base/files/file_util.h" #include "base/files/file_util.h"
#include "crypto/hash.h"
#include "crypto/sha2.h" #include "crypto/sha2.h"
#include "net/cert/asn1_util.h" #include "net/cert/asn1_util.h"
#include "net/cert/x509_certificate.h" #include "net/cert/x509_certificate.h"
@@ -187,8 +188,7 @@ TEST(CRLSetTest, BlockedSubjects) {
std::string_view spki; std::string_view spki;
ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(root_der, &spki)); ASSERT_TRUE(asn1::ExtractSPKIFromDERCert(root_der, &spki));
SHA256HashValue spki_sha256; SHA256HashValue spki_sha256 = crypto::hash::Sha256(base::as_byte_span(spki));
crypto::SHA256HashString(spki, spki_sha256.data, sizeof(spki_sha256.data));
std::string_view subject; std::string_view subject;
ASSERT_TRUE(asn1::ExtractSubjectFromDERCert(root_der, &subject)); ASSERT_TRUE(asn1::ExtractSubjectFromDERCert(root_der, &subject));
@@ -206,10 +206,7 @@ TEST(CRLSetTest, BlockedSubjects) {
// When used with the correct hash, that subject should be accepted. // When used with the correct hash, that subject should be accepted.
EXPECT_EQ(CRLSet::GOOD, EXPECT_EQ(CRLSet::GOOD,
set->CheckSubject( set->CheckSubject(subject, base::as_string_view(spki_sha256)));
subject, std::string_view(
reinterpret_cast<const char*>(spki_sha256.data),
sizeof(spki_sha256.data))));
} }
TEST(CRLSetTest, Expired) { TEST(CRLSetTest, Expired) {

@@ -595,17 +595,15 @@ namespace rfc6962 {
std::string HashLeaf(const std::string& leaf) { std::string HashLeaf(const std::string& leaf) {
const char kLeafPrefix[] = {'\x00'}; const char kLeafPrefix[] = {'\x00'};
SHA256HashValue sha256; SHA256HashValue sha256 = {0};
memset(sha256.data, 0, sizeof(sha256.data));
std::unique_ptr<crypto::SecureHash> hash( std::unique_ptr<crypto::SecureHash> hash(
crypto::SecureHash::Create(crypto::SecureHash::SHA256)); crypto::SecureHash::Create(crypto::SecureHash::SHA256));
hash->Update(kLeafPrefix, 1); hash->Update(kLeafPrefix, 1);
hash->Update(leaf.data(), leaf.size()); hash->Update(leaf.data(), leaf.size());
hash->Finish(sha256.data, sizeof(sha256.data)); hash->Finish(sha256);
return std::string(reinterpret_cast<const char*>(sha256.data), return std::string(base::as_string_view(sha256));
sizeof(sha256.data));
} }
// Calculates the root hash of a Merkle tree, given its leaf data and size. // Calculates the root hash of a Merkle tree, given its leaf data and size.

@@ -17,6 +17,7 @@
#include "base/hash/sha1.h" #include "base/hash/sha1.h"
#include "base/logging.h" #include "base/logging.h"
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "crypto/hash.h"
#include "crypto/sha2.h" #include "crypto/sha2.h"
#include "net/cert/asn1_util.h" #include "net/cert/asn1_util.h"
#include "net/cert/signed_certificate_timestamp.h" #include "net/cert/signed_certificate_timestamp.h"
@@ -334,8 +335,8 @@ bool GetPrecertSignedEntry(const CRYPTO_BUFFER* leaf,
result->type = ct::SignedEntryData::LOG_ENTRY_TYPE_PRECERT; result->type = ct::SignedEntryData::LOG_ENTRY_TYPE_PRECERT;
result->tbs_certificate.assign( result->tbs_certificate.assign(
reinterpret_cast<const char*>(new_tbs_cert_der), new_tbs_cert_len); reinterpret_cast<const char*>(new_tbs_cert_der), new_tbs_cert_len);
crypto::SHA256HashString(issuer_key, result->issuer_key_hash.data, result->issuer_key_hash =
sizeof(result->issuer_key_hash.data)); crypto::hash::Sha256(base::as_byte_span(issuer_key));
return true; return true;
} }

@@ -101,9 +101,8 @@ TEST_F(CTObjectsExtractorTest, ExtractPrecert) {
// Should have empty leaf cert for this log entry type. // Should have empty leaf cert for this log entry type.
ASSERT_TRUE(entry.leaf_certificate.empty()); ASSERT_TRUE(entry.leaf_certificate.empty());
// Compare hash values of issuer spki. // Compare hash values of issuer spki.
SHA256HashValue expected_issuer_key_hash; ASSERT_EQ(base::as_byte_span(GetDefaultIssuerKeyHash()),
memcpy(expected_issuer_key_hash.data, GetDefaultIssuerKeyHash().data(), 32); entry.issuer_key_hash);
ASSERT_EQ(expected_issuer_key_hash, entry.issuer_key_hash);
} }
TEST_F(CTObjectsExtractorTest, ExtractOrdinaryX509Cert) { TEST_F(CTObjectsExtractorTest, ExtractOrdinaryX509Cert) {

@@ -114,10 +114,7 @@ bool EncodeAsn1CertSignedEntry(const SignedEntryData& input, CBB* output) {
// does not exceed kMaxTbsCertificateLength and so can be written to |output|. // does not exceed kMaxTbsCertificateLength and so can be written to |output|.
bool EncodePrecertSignedEntry(const SignedEntryData& input, CBB* output) { bool EncodePrecertSignedEntry(const SignedEntryData& input, CBB* output) {
CBB child; CBB child;
return CBB_add_bytes( return CBB_add_bytes(output, input.issuer_key_hash.data(), kLogIdLength) &&
output,
reinterpret_cast<const uint8_t*>(input.issuer_key_hash.data),
kLogIdLength) &&
CBB_add_u24_length_prefixed(output, &child) && CBB_add_u24_length_prefixed(output, &child) &&
CBB_add_bytes( CBB_add_bytes(
&child, &child,

@@ -105,8 +105,7 @@ TEST_F(CtSerializationTest, EncodesSignedEntryForPrecert) {
// First two bytes are the log entry type. // First two bytes are the log entry type.
EXPECT_EQ(std::string("\x00\x01", 2), encoded.substr(0, 2)); EXPECT_EQ(std::string("\x00\x01", 2), encoded.substr(0, 2));
// Next comes the 32-byte issuer key hash // Next comes the 32-byte issuer key hash
EXPECT_THAT(encoded.substr(2, 32), EXPECT_THAT(encoded.substr(2, 32), ElementsAreArray(entry.issuer_key_hash));
ElementsAreArray(entry.issuer_key_hash.data));
// Then the length of the TBS cert (604 bytes = 0x237) // Then the length of the TBS cert (604 bytes = 0x237)
EXPECT_EQ(std::string("\x00\x02\x37", 3), encoded.substr(34, 3)); EXPECT_EQ(std::string("\x00\x02\x37", 3), encoded.substr(34, 3));
// Then the TBS cert itself // Then the TBS cert itself
@@ -240,7 +239,7 @@ TEST_F(CtSerializationTest, EncodesMerkleTreeLeafForPrecert) {
EXPECT_EQ(std::string("\x00\x01", 2), encoded.substr(10, 2)) << EXPECT_EQ(std::string("\x00\x01", 2), encoded.substr(10, 2)) <<
"Log entry type encoded incorrectly"; "Log entry type encoded incorrectly";
EXPECT_THAT(encoded.substr(12, 32), EXPECT_THAT(encoded.substr(12, 32),
ElementsAreArray(tree_leaf.signed_entry.issuer_key_hash.data)) ElementsAreArray(tree_leaf.signed_entry.issuer_key_hash))
<< "Issuer key hash encoded incorrectly"; << "Issuer key hash encoded incorrectly";
EXPECT_EQ(std::string("\x00\x02\x37", 3), encoded.substr(44, 3)) << EXPECT_EQ(std::string("\x00\x02\x37", 3), encoded.substr(44, 3)) <<
"TBS certificate length encoded incorrectly"; "TBS certificate length encoded incorrectly";

@@ -456,7 +456,7 @@ class TrustDomainCacheFullCerts {
SHA256HashValue CalculateFingerprint256(const bssl::der::Input& buffer) { SHA256HashValue CalculateFingerprint256(const bssl::der::Input& buffer) {
SHA256HashValue sha256; SHA256HashValue sha256;
SHA256(buffer.data(), buffer.size(), sha256.data); SHA256(buffer.data(), buffer.size(), sha256.data());
return sha256; return sha256;
} }

@@ -666,13 +666,12 @@ SHA256HashValue X509Certificate::CalculateFingerprint256(
const CRYPTO_BUFFER* cert) { const CRYPTO_BUFFER* cert) {
SHA256HashValue sha256; SHA256HashValue sha256;
SHA256(CRYPTO_BUFFER_data(cert), CRYPTO_BUFFER_len(cert), sha256.data); SHA256(CRYPTO_BUFFER_data(cert), CRYPTO_BUFFER_len(cert), sha256.data());
return sha256; return sha256;
} }
SHA256HashValue X509Certificate::CalculateChainFingerprint256() const { SHA256HashValue X509Certificate::CalculateChainFingerprint256() const {
SHA256HashValue sha256; SHA256HashValue sha256 = {0};
memset(sha256.data, 0, sizeof(sha256.data));
SHA256_CTX sha256_ctx; SHA256_CTX sha256_ctx;
SHA256_Init(&sha256_ctx); SHA256_Init(&sha256_ctx);
@@ -682,7 +681,7 @@ SHA256HashValue X509Certificate::CalculateChainFingerprint256() const {
SHA256_Update(&sha256_ctx, CRYPTO_BUFFER_data(cert.get()), SHA256_Update(&sha256_ctx, CRYPTO_BUFFER_data(cert.get()),
CRYPTO_BUFFER_len(cert.get())); CRYPTO_BUFFER_len(cert.get()));
} }
SHA256_Final(sha256.data, &sha256_ctx); SHA256_Final(sha256.data(), &sha256_ctx);
return sha256; return sha256;
} }

@@ -129,8 +129,7 @@ scoped_refptr<X509Certificate> CreateX509CertificateFromSecCertificate(
} }
SHA256HashValue CalculateFingerprint256(SecCertificateRef cert) { SHA256HashValue CalculateFingerprint256(SecCertificateRef cert) {
SHA256HashValue sha256; SHA256HashValue sha256 = {0};
memset(sha256.data, 0, sizeof(sha256.data));
base::apple::ScopedCFTypeRef<CFDataRef> cert_data( base::apple::ScopedCFTypeRef<CFDataRef> cert_data(
SecCertificateCopyData(cert)); SecCertificateCopyData(cert));
@@ -142,7 +141,7 @@ SHA256HashValue CalculateFingerprint256(SecCertificateRef cert) {
DCHECK_NE(CFDataGetLength(cert_data.get()), 0); DCHECK_NE(CFDataGetLength(cert_data.get()), 0);
CC_SHA256(CFDataGetBytePtr(cert_data.get()), CFDataGetLength(cert_data.get()), CC_SHA256(CFDataGetBytePtr(cert_data.get()), CFDataGetLength(cert_data.get()),
sha256.data); sha256.data());
return sha256; return sha256;
} }

@@ -438,13 +438,12 @@ bool GetValidityTimes(CERTCertificate* cert,
} }
SHA256HashValue CalculateFingerprint256(CERTCertificate* cert) { SHA256HashValue CalculateFingerprint256(CERTCertificate* cert) {
SHA256HashValue sha256; SHA256HashValue sha256 = {0};
memset(sha256.data, 0, sizeof(sha256.data));
DCHECK(cert->derCert.data); DCHECK(cert->derCert.data);
DCHECK_NE(0U, cert->derCert.len); DCHECK_NE(0U, cert->derCert.len);
SECStatus rv = HASH_HashBuf(HASH_AlgSHA256, sha256.data, cert->derCert.data, SECStatus rv = HASH_HashBuf(HASH_AlgSHA256, sha256.data(), cert->derCert.data,
cert->derCert.len); cert->derCert.len);
DCHECK_EQ(SECSuccess, rv); DCHECK_EQ(SECSuccess, rv);

@@ -7,6 +7,7 @@
#include <string_view> #include <string_view>
#include "base/logging.h" #include "base/logging.h"
#include "crypto/hash.h"
#include "crypto/scoped_capi_types.h" #include "crypto/scoped_capi_types.h"
#include "crypto/sha2.h" #include "crypto/sha2.h"
#include "net/cert/x509_certificate.h" #include "net/cert/x509_certificate.h"
@@ -102,15 +103,11 @@ SHA256HashValue CalculateFingerprint256(PCCERT_CONTEXT cert) {
DCHECK(nullptr != cert->pbCertEncoded); DCHECK(nullptr != cert->pbCertEncoded);
DCHECK_NE(0u, cert->cbCertEncoded); DCHECK_NE(0u, cert->cbCertEncoded);
SHA256HashValue sha256; // Use crypto::SHA256Hash for two reasons:
// Use crypto::SHA256HashString for two reasons:
// * < Windows Vista does not have universal SHA-256 support. // * < Windows Vista does not have universal SHA-256 support.
// * More efficient on Windows > Vista (less overhead since non-default CSP // * More efficient on Windows > Vista (less overhead since non-default CSP
// is not needed). // is not needed).
crypto::SHA256HashString(base::as_string_view(CertContextAsSpan(cert)), return crypto::hash::Sha256(CertContextAsSpan(cert));
sha256.data, sizeof(sha256.data));
return sha256;
} }
bool IsSelfSigned(PCCERT_CONTEXT cert_handle) { bool IsSelfSigned(PCCERT_CONTEXT cert_handle) {

@@ -97,7 +97,7 @@ void CalculateSHA256OfKey(const std::string& key,
std::unique_ptr<crypto::SecureHash> hash( std::unique_ptr<crypto::SecureHash> hash(
crypto::SecureHash::Create(crypto::SecureHash::SHA256)); crypto::SecureHash::Create(crypto::SecureHash::SHA256));
hash->Update(key.data(), key.size()); hash->Update(key.data(), key.size());
hash->Finish(out_hash_value, sizeof(*out_hash_value)); hash->Finish(*out_hash_value);
} }
SimpleFileTracker::SubFile SubFileForFileIndex(int file_index) { SimpleFileTracker::SubFile SubFileForFileIndex(int file_index) {
@@ -1102,7 +1102,7 @@ void SimpleSynchronousEntry::Close(
net::SHA256HashValue hash_value; net::SHA256HashValue hash_value;
CalculateSHA256OfKey(key, &hash_value); CalculateSHA256OfKey(key, &hash_value);
if (!file->WriteAndCheck(stream_0_offset + entry_stat.data_size(0), if (!file->WriteAndCheck(stream_0_offset + entry_stat.data_size(0),
base::byte_span_from_ref(hash_value))) { hash_value)) {
RecordCloseResult(cache_type_, CLOSE_RESULT_WRITE_FAILURE); RecordCloseResult(cache_type_, CLOSE_RESULT_WRITE_FAILURE);
DVLOG(1) << "Could not write stream 0 data."; DVLOG(1) << "Could not write stream 0 data.";
DoomInternal(file_operations.get()); DoomInternal(file_operations.get());

@@ -132,10 +132,10 @@ bool CreateV3Schema(sql::Database* db, sql::MetaTable* meta_table) {
std::optional<SHA256HashValue> ToSHA256HashValue( std::optional<SHA256HashValue> ToSHA256HashValue(
base::span<const uint8_t> sha256_bytes) { base::span<const uint8_t> sha256_bytes) {
SHA256HashValue sha256_hash; SHA256HashValue sha256_hash;
if (sha256_bytes.size() != sizeof(sha256_hash.data)) { if (sha256_bytes.size() != sha256_hash.size()) {
return std::nullopt; return std::nullopt;
} }
memcpy(sha256_hash.data, sha256_bytes.data(), sha256_bytes.size()); memcpy(sha256_hash.data(), sha256_bytes.data(), sha256_bytes.size());
return sha256_hash; return sha256_hash;
} }
@@ -570,7 +570,7 @@ SQLitePersistentSharedDictionaryStore::Backend::RegisterDictionaryImpl(
statement.BindTime(9, dictionary_info.GetExpirationTime()); statement.BindTime(9, dictionary_info.GetExpirationTime());
statement.BindTime(10, dictionary_info.last_used_time()); statement.BindTime(10, dictionary_info.last_used_time());
statement.BindInt64(11, dictionary_info.size()); statement.BindInt64(11, dictionary_info.size());
statement.BindBlob(12, base::span(dictionary_info.hash().data)); statement.BindBlob(12, base::span(dictionary_info.hash()));
// There is no `sql::Statement::BindUint64()` method. So we cast to int64_t. // There is no `sql::Statement::BindUint64()` method. So we cast to int64_t.
int64_t token_high = static_cast<int64_t>( int64_t token_high = static_cast<int64_t>(
dictionary_info.disk_cache_key_token().GetHighForSerialization()); dictionary_info.disk_cache_key_token().GetHighForSerialization());

@@ -9,11 +9,11 @@
#include "base/functional/callback.h" #include "base/functional/callback.h"
#include "base/memory/ref_counted.h" #include "base/memory/ref_counted.h"
#include "net/base/hash_value.h"
#include "net/base/net_export.h" #include "net/base/net_export.h"
namespace net { namespace net {
class IOBuffer; class IOBuffer;
struct SHA256HashValue;
// This class is used to read the binary of the shared dictionary. // This class is used to read the binary of the shared dictionary.
class NET_EXPORT SharedDictionary : public base::RefCounted<SharedDictionary> { class NET_EXPORT SharedDictionary : public base::RefCounted<SharedDictionary> {

@@ -145,7 +145,7 @@ bool SharedDictionaryHeaderCheckerSourceStream::CheckHeaderBuffer() const {
if (GetSignatureInBuffer() != GetExpectedSignature(type_)) { if (GetSignatureInBuffer() != GetExpectedSignature(type_)) {
return false; return false;
} }
if (GetHashInBuffer() != base::span(dictionary_hash_.data)) { if (GetHashInBuffer() != dictionary_hash_) {
return false; return false;
} }
return true; return true;

@@ -260,7 +260,7 @@ TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, HeaderSync) {
TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, HeaderSplittedSync) { TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, HeaderSplittedSync) {
AddReadResult(GetSignature(), Mode::SYNC); AddReadResult(GetSignature(), Mode::SYNC);
AddReadResult(kTestHash.data, Mode::SYNC); AddReadResult(kTestHash, Mode::SYNC);
AddReadResult(kTestBodyData, Mode::SYNC); AddReadResult(kTestBodyData, Mode::SYNC);
AddReadResult(OK, Mode::SYNC); AddReadResult(OK, Mode::SYNC);
CreateHeaderCheckerSourceStream(); CreateHeaderCheckerSourceStream();
@@ -283,7 +283,7 @@ TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, HeaderAsync) {
TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, HeaderSplittedAsync) { TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, HeaderSplittedAsync) {
AddReadResult(GetSignature(), Mode::ASYNC); AddReadResult(GetSignature(), Mode::ASYNC);
AddReadResult(kTestHash.data, Mode::ASYNC); AddReadResult(kTestHash, Mode::ASYNC);
AddReadResult(kTestBodyData, Mode::ASYNC); AddReadResult(kTestBodyData, Mode::ASYNC);
AddReadResult(OK, Mode::ASYNC); AddReadResult(OK, Mode::ASYNC);
CreateHeaderCheckerSourceStream(); CreateHeaderCheckerSourceStream();
@@ -295,14 +295,14 @@ TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, HeaderSplittedAsync) {
TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongSinatureSync) { TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongSinatureSync) {
AddReadResult(GetWrongSignature(), Mode::SYNC); AddReadResult(GetWrongSignature(), Mode::SYNC);
AddReadResult(kTestHash.data, Mode::SYNC); AddReadResult(kTestHash, Mode::SYNC);
CreateHeaderCheckerSourceStream(); CreateHeaderCheckerSourceStream();
CheckSyncRead(ERR_UNEXPECTED_CONTENT_DICTIONARY_HEADER); CheckSyncRead(ERR_UNEXPECTED_CONTENT_DICTIONARY_HEADER);
} }
TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongSinatureAsync) { TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongSinatureAsync) {
AddReadResult(GetWrongSignature(), Mode::ASYNC); AddReadResult(GetWrongSignature(), Mode::ASYNC);
AddReadResult(kTestHash.data, Mode::ASYNC); AddReadResult(kTestHash, Mode::ASYNC);
CreateHeaderCheckerSourceStream(); CreateHeaderCheckerSourceStream();
CheckAsyncRead(ERR_UNEXPECTED_CONTENT_DICTIONARY_HEADER, 2); CheckAsyncRead(ERR_UNEXPECTED_CONTENT_DICTIONARY_HEADER, 2);
} }
@@ -310,7 +310,7 @@ TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongSinatureAsync) {
TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongHashSync) { TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongHashSync) {
const SHA256HashValue kWrongHash = {{0x01}}; const SHA256HashValue kWrongHash = {{0x01}};
AddReadResult(GetSignature(), Mode::SYNC); AddReadResult(GetSignature(), Mode::SYNC);
AddReadResult(kWrongHash.data, Mode::SYNC); AddReadResult(kWrongHash, Mode::SYNC);
CreateHeaderCheckerSourceStream(); CreateHeaderCheckerSourceStream();
CheckSyncRead(ERR_UNEXPECTED_CONTENT_DICTIONARY_HEADER); CheckSyncRead(ERR_UNEXPECTED_CONTENT_DICTIONARY_HEADER);
} }
@@ -318,7 +318,7 @@ TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongHashSync) {
TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongHashAsync) { TEST_P(SharedDictionaryHeaderCheckerSourceStreamTest, WrongHashAsync) {
const SHA256HashValue kWrongHash = {{0x01}}; const SHA256HashValue kWrongHash = {{0x01}};
AddReadResult(GetSignature(), Mode::ASYNC); AddReadResult(GetSignature(), Mode::ASYNC);
AddReadResult(kWrongHash.data, Mode::ASYNC); AddReadResult(kWrongHash, Mode::ASYNC);
CreateHeaderCheckerSourceStream(); CreateHeaderCheckerSourceStream();
CheckAsyncRead(ERR_UNEXPECTED_CONTENT_DICTIONARY_HEADER, 2); CheckAsyncRead(ERR_UNEXPECTED_CONTENT_DICTIONARY_HEADER, 2);
} }

@@ -222,8 +222,8 @@ void SharedDictionaryNetworkTransaction::ModifyRequestHeaders(
shared_dictionary_.reset(); shared_dictionary_.reset();
return; return;
} }
dictionary_hash_base64_ = base::StrCat( dictionary_hash_base64_ =
{":", base::Base64Encode(shared_dictionary_->hash().data), ":"}); base::StrCat({":", base::Base64Encode(shared_dictionary_->hash()), ":"});
request_headers->SetHeader(shared_dictionary::kAvailableDictionaryHeaderName, request_headers->SetHeader(shared_dictionary::kAvailableDictionaryHeaderName,
dictionary_hash_base64_); dictionary_hash_base64_);
if (enable_shared_zstd_) { if (enable_shared_zstd_) {

@@ -94,7 +94,7 @@ class DummySyncDictionary : public SharedDictionary {
std::unique_ptr<crypto::SecureHash> secure_hash = std::unique_ptr<crypto::SecureHash> secure_hash =
crypto::SecureHash::Create(crypto::SecureHash::SHA256); crypto::SecureHash::Create(crypto::SecureHash::SHA256);
secure_hash->Update(data_->data(), size_); secure_hash->Update(data_->data(), size_);
secure_hash->Finish(hash_.data, sizeof(hash_.data)); secure_hash->Finish(hash_);
} }
// SharedDictionary // SharedDictionary

@@ -27,6 +27,7 @@
#include "base/strings/string_util.h" #include "base/strings/string_util.h"
#include "base/time/time.h" #include "base/time/time.h"
#include "crypto/ec_private_key.h" #include "crypto/ec_private_key.h"
#include "crypto/hash.h"
#include "crypto/rsa_private_key.h" #include "crypto/rsa_private_key.h"
#include "crypto/sha2.h" #include "crypto/sha2.h"
#include "net/cert/asn1_util.h" #include "net/cert/asn1_util.h"
@@ -1416,9 +1417,8 @@ void CertBuilder::BuildSctListExtension(const std::string& pre_tbs_certificate,
ASSERT_TRUE(CBB_init(issuer_spki_cbb.get(), 32)); ASSERT_TRUE(CBB_init(issuer_spki_cbb.get(), 32));
ASSERT_TRUE( ASSERT_TRUE(
EVP_marshal_public_key(issuer_spki_cbb.get(), issuer_->GetKey())); EVP_marshal_public_key(issuer_spki_cbb.get(), issuer_->GetKey()));
crypto::SHA256HashString(FinishCBB(issuer_spki_cbb.get()), entry.issuer_key_hash = crypto::hash::Sha256(
entry.issuer_key_hash.data, base::as_byte_span(FinishCBB(issuer_spki_cbb.get())));
sizeof(entry.issuer_key_hash.data));
entry.tbs_certificate = pre_tbs_certificate; entry.tbs_certificate = pre_tbs_certificate;
std::string serialized_log_entry; std::string serialized_log_entry;

@@ -187,8 +187,8 @@ std::string GetDerEncodedX509Cert() {
void GetPrecertSignedEntry(SignedEntryData* entry) { void GetPrecertSignedEntry(SignedEntryData* entry) {
entry->type = ct::SignedEntryData::LOG_ENTRY_TYPE_PRECERT; entry->type = ct::SignedEntryData::LOG_ENTRY_TYPE_PRECERT;
std::string issuer_hash(HexDecode(kDefaultIssuerKeyHash)); base::span(entry->issuer_key_hash)
memcpy(entry->issuer_key_hash.data, issuer_hash.data(), issuer_hash.size()); .copy_from(base::as_byte_span(HexDecode(kDefaultIssuerKeyHash)));
entry->tbs_certificate = HexDecode(kDefaultDerTbsCert); entry->tbs_certificate = HexDecode(kDefaultDerTbsCert);
} }

@@ -122,7 +122,7 @@ void PrintCertError(const std::string& error, const CertInput& cert) {
std::string FingerPrintCryptoBuffer(const CRYPTO_BUFFER* cert_handle) { std::string FingerPrintCryptoBuffer(const CRYPTO_BUFFER* cert_handle) {
net::SHA256HashValue hash = net::SHA256HashValue hash =
net::X509Certificate::CalculateFingerprint256(cert_handle); net::X509Certificate::CalculateFingerprint256(cert_handle);
return base::HexEncode(hash.data); return base::HexEncode(hash);
} }
std::string SubjectFromX509Certificate(const net::X509Certificate* cert) { std::string SubjectFromX509Certificate(const net::X509Certificate* cert) {

@@ -112,7 +112,7 @@ internal::CertVerifierServiceImpl* GetNewCertVerifierImpl(
std::string GetHash(const bssl::ParsedCertificate& cert) { std::string GetHash(const bssl::ParsedCertificate& cert) {
net::SHA256HashValue hash = net::SHA256HashValue hash =
net::X509Certificate::CalculateFingerprint256(cert.cert_buffer()); net::X509Certificate::CalculateFingerprint256(cert.cert_buffer());
return base::HexEncode(hash.data); return base::HexEncode(hash);
} }
bool IsVersionConstraintSatisified( bool IsVersionConstraintSatisified(

@@ -482,7 +482,7 @@ TEST(CertVerifierServiceFactoryTest, RootStoreInfoWithUpdatedRootStore) {
net::SHA256HashValue root_hash = net::SHA256HashValue root_hash =
net::X509Certificate::CalculateFingerprint256(root->GetCertBuffer()); net::X509Certificate::CalculateFingerprint256(root->GetCertBuffer());
EXPECT_EQ(info_ptr->root_cert_info[0]->sha256hash_hex, EXPECT_EQ(info_ptr->root_cert_info[0]->sha256hash_hex,
base::HexEncode(root_hash.data)); base::HexEncode(root_hash));
EXPECT_TRUE(net::x509_util::CryptoBufferEqual( EXPECT_TRUE(net::x509_util::CryptoBufferEqual(
net::x509_util::CreateCryptoBuffer(info_ptr->root_cert_info[0]->cert) net::x509_util::CreateCryptoBuffer(info_ptr->root_cert_info[0]->cert)
.get(), .get(),

@@ -59,7 +59,7 @@ static std::vector<std::string> MakeAllowlist() {
&cert_spki); &cert_spki);
crypto::SHA256HashString(cert_spki, &hash, sizeof(SHA256HashValue)); crypto::SHA256HashString(cert_spki, &hash, sizeof(SHA256HashValue));
std::string hash_base64 = base::Base64Encode(hash.data); std::string hash_base64 = base::Base64Encode(hash);
return {"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", "foobar", hash_base64, return {"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=", "foobar", hash_base64,
"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB="}; "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB="};
} }

@@ -7,9 +7,11 @@
#pragma allow_unsafe_libc_calls #pragma allow_unsafe_libc_calls
#endif #endif
#include "services/network/public/cpp/hash_value_mojom_traits.h"
#include <string.h> #include <string.h>
#include "services/network/public/cpp/hash_value_mojom_traits.h" #include "base/containers/span.h"
namespace mojo { namespace mojo {
@@ -25,7 +27,7 @@ bool StructTraits<
// CHECK it instead when it does. // CHECK it instead when it does.
return false; return false;
} }
memcpy(out->data, bytes.data(), bytes.size()); base::span(*out).copy_from(base::as_byte_span(bytes));
return true; return true;
} }

@@ -15,7 +15,7 @@ template <>
struct StructTraits<network::mojom::SHA256HashValueDataView, struct StructTraits<network::mojom::SHA256HashValueDataView,
net::SHA256HashValue> { net::SHA256HashValue> {
static base::span<const uint8_t, 32> data(const net::SHA256HashValue& value) { static base::span<const uint8_t, 32> data(const net::SHA256HashValue& value) {
return value.data; return value;
} }
static bool Read(network::mojom::SHA256HashValueDataView in, static bool Read(network::mojom::SHA256HashValueDataView in,

@@ -7,10 +7,7 @@
#include "base/component_export.h" #include "base/component_export.h"
#include "base/containers/flat_set.h" #include "base/containers/flat_set.h"
#include "net/base/hash_value.h"
namespace net {
struct SHA256HashValue;
} // namespace net
namespace network { namespace network {

@@ -1112,7 +1112,7 @@ TEST_P(SharedDictionaryManagerTest, WriteAndReadDictionary) {
secure_hash->Update(data1.c_str(), data1.size()); secure_hash->Update(data1.c_str(), data1.size());
secure_hash->Update(data2.c_str(), data2.size()); secure_hash->Update(data2.c_str(), data2.size());
net::SHA256HashValue sha256; net::SHA256HashValue sha256;
secure_hash->Finish(sha256.data, sizeof(sha256.data)); secure_hash->Finish(sha256);
if (GetManagerType() == TestManagerType::kOnDisk) { if (GetManagerType() == TestManagerType::kOnDisk) {
FlushCacheTasks(); FlushCacheTasks();

@@ -58,7 +58,7 @@ void SharedDictionaryWriterInMemory::Finish() {
} }
net::SHA256HashValue sha256; net::SHA256HashValue sha256;
secure_hash_->Finish(sha256.data, sizeof(sha256.data)); secure_hash_->Finish(sha256);
if (total_size_ == 0) { if (total_size_ == 0) {
std::move(finish_callback_) std::move(finish_callback_)

@@ -12,11 +12,11 @@
#include "base/component_export.h" #include "base/component_export.h"
#include "base/functional/callback.h" #include "base/functional/callback.h"
#include "crypto/secure_hash.h" #include "crypto/secure_hash.h"
#include "net/base/hash_value.h"
#include "services/network/shared_dictionary/shared_dictionary_writer.h" #include "services/network/shared_dictionary/shared_dictionary_writer.h"
namespace net { namespace net {
class IOBuffer; class IOBuffer;
struct SHA256HashValue;
} // namespace net } // namespace net
namespace network { namespace network {

@@ -25,7 +25,7 @@ net::SHA256HashValue GetHash(const std::string& data) {
crypto::SecureHash::Create(crypto::SecureHash::SHA256); crypto::SecureHash::Create(crypto::SecureHash::SHA256);
secure_hash->Update(data.c_str(), data.size()); secure_hash->Update(data.c_str(), data.size());
net::SHA256HashValue sha256; net::SHA256HashValue sha256;
secure_hash->Finish(sha256.data, sizeof(sha256.data)); secure_hash->Finish(sha256);
return sha256; return sha256;
} }

@@ -174,7 +174,7 @@ void SharedDictionaryWriterOnDisk::MaybeFinish() {
entry_.reset(); entry_.reset();
DCHECK_EQ(written_size_, total_size_); DCHECK_EQ(written_size_, total_size_);
net::SHA256HashValue sha256; net::SHA256HashValue sha256;
secure_hash_->Finish(sha256.data, sizeof(sha256.data)); secure_hash_->Finish(sha256);
std::move(callback_).Run(Result::kSuccess, total_size_, sha256); std::move(callback_).Run(Result::kSuccess, total_size_, sha256);
} }

@@ -41,7 +41,7 @@ net::SHA256HashValue GetHash(const std::string& data) {
crypto::SecureHash::Create(crypto::SecureHash::SHA256); crypto::SecureHash::Create(crypto::SecureHash::SHA256);
secure_hash->Update(data.c_str(), data.size()); secure_hash->Update(data.c_str(), data.size());
net::SHA256HashValue sha256; net::SHA256HashValue sha256;
secure_hash->Finish(sha256.data, sizeof(sha256.data)); secure_hash->Finish(sha256);
return sha256; return sha256;
} }

@@ -9,6 +9,7 @@
#include "third_party/blink/public/common/navigation/prefetched_signed_exchange_info_mojom_traits.h" #include "third_party/blink/public/common/navigation/prefetched_signed_exchange_info_mojom_traits.h"
#include "base/containers/span.h"
#include "base/notreached.h" #include "base/notreached.h"
namespace mojo { namespace mojo {
@@ -20,11 +21,11 @@ bool StructTraits<blink::mojom::SHA256HashValueDataView, net::SHA256HashValue>::
if (!input.ReadData(&data)) if (!input.ReadData(&data))
return false; return false;
if (data.size() != sizeof(out->data)) { if (data.size() != out->size()) {
NOTREACHED(); NOTREACHED();
} }
memcpy(out->data, data.c_str(), sizeof(out->data)); base::span(*out).copy_from(base::as_byte_span(data));
return true; return true;
} }

@@ -7,6 +7,7 @@
#include <string> #include <string>
#include "base/containers/span.h"
#include "mojo/public/cpp/base/byte_string_mojom_traits.h" #include "mojo/public/cpp/base/byte_string_mojom_traits.h"
#include "mojo/public/cpp/bindings/struct_traits.h" #include "mojo/public/cpp/bindings/struct_traits.h"
#include "net/base/hash_value.h" #include "net/base/hash_value.h"
@@ -19,8 +20,7 @@ template <>
struct BLINK_COMMON_EXPORT struct BLINK_COMMON_EXPORT
StructTraits<blink::mojom::SHA256HashValueDataView, net::SHA256HashValue> { StructTraits<blink::mojom::SHA256HashValueDataView, net::SHA256HashValue> {
static const std::string data(const net::SHA256HashValue& value) { static const std::string data(const net::SHA256HashValue& value) {
return std::string(reinterpret_cast<const char*>(value.data), return std::string(base::as_string_view(value));
sizeof(value.data));
} }
static bool Read(blink::mojom::SHA256HashValueDataView input, static bool Read(blink::mojom::SHA256HashValueDataView input,