cast_cert_reader.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "components/cast_certificate/cast_cert_reader.h"
  5. #include "base/files/file_util.h"
  6. #include "base/logging.h"
  7. #include "base/path_service.h"
  8. #include "net/cert/pem.h"
  9. #include "net/cert/pki/common_cert_errors.h"
  10. #include "net/cert/x509_util.h"
  11. namespace cast_certificate {
  12. bool PopulateStoreWithCertsFromPath(net::TrustStoreInMemory* store,
  13. const base::FilePath& path) {
  14. const std::vector<std::string> trusted_roots =
  15. ReadCertificateChainFromFile(path);
  16. for (const auto& trusted_root : trusted_roots) {
  17. net::CertErrors errors;
  18. scoped_refptr<net::ParsedCertificate> cert(net::ParsedCertificate::Create(
  19. net::x509_util::CreateCryptoBuffer(trusted_root), {}, &errors));
  20. if (errors.ContainsAnyErrorWithSeverity(
  21. net::CertError::Severity::SEVERITY_HIGH)) {
  22. LOG(ERROR) << "Failed to load cert due to following error(s): "
  23. << errors.ToDebugString();
  24. return false;
  25. }
  26. store->AddTrustAnchorWithConstraints(cert);
  27. }
  28. return true;
  29. }
  30. std::vector<std::string> ReadCertificateChainFromFile(
  31. const base::FilePath& path) {
  32. std::string file_data;
  33. if (!base::ReadFileToString(path, &file_data)) {
  34. LOG(ERROR) << "Failed to read certificate chain from file: " << path;
  35. return {};
  36. }
  37. return ReadCertificateChainFromString(file_data.data());
  38. }
  39. std::vector<std::string> ReadCertificateChainFromString(const char* str) {
  40. std::vector<std::string> certs;
  41. net::PEMTokenizer pem_tokenizer(str, {"CERTIFICATE"});
  42. while (pem_tokenizer.GetNext())
  43. certs.push_back(pem_tokenizer.data());
  44. if (certs.empty()) {
  45. LOG(WARNING) << "Certificate chain is empty.";
  46. }
  47. return certs;
  48. }
  49. } // namespace cast_certificate