key_util.cc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2019 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 "net/test/key_util.h"
  5. #include <string>
  6. #include <utility>
  7. #include "base/files/file_util.h"
  8. #include "base/logging.h"
  9. #include "net/ssl/ssl_private_key.h"
  10. #include "net/ssl/test_ssl_private_key.h"
  11. #include "third_party/boringssl/src/include/openssl/bio.h"
  12. #include "third_party/boringssl/src/include/openssl/evp.h"
  13. #include "third_party/boringssl/src/include/openssl/pem.h"
  14. namespace net::key_util {
  15. bssl::UniquePtr<EVP_PKEY> LoadEVP_PKEYFromPEM(const base::FilePath& filepath) {
  16. std::string data;
  17. if (!base::ReadFileToString(filepath, &data)) {
  18. LOG(ERROR) << "Could not read private key file: " << filepath.value();
  19. return nullptr;
  20. }
  21. bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(const_cast<char*>(data.data()),
  22. static_cast<int>(data.size())));
  23. if (!bio) {
  24. LOG(ERROR) << "Could not allocate BIO for buffer?";
  25. return nullptr;
  26. }
  27. bssl::UniquePtr<EVP_PKEY> result(
  28. PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
  29. if (!result) {
  30. LOG(ERROR) << "Could not decode private key file: " << filepath.value();
  31. return nullptr;
  32. }
  33. return result;
  34. }
  35. scoped_refptr<SSLPrivateKey> LoadPrivateKeyOpenSSL(
  36. const base::FilePath& filepath) {
  37. bssl::UniquePtr<EVP_PKEY> key = LoadEVP_PKEYFromPEM(filepath);
  38. if (!key)
  39. return nullptr;
  40. return WrapOpenSSLPrivateKey(std::move(key));
  41. }
  42. } // namespace net::key_util