• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/test/key_util.h"
6 
7 #include <string>
8 #include <utility>
9 
10 #include "base/files/file_util.h"
11 #include "base/logging.h"
12 #include "net/ssl/ssl_private_key.h"
13 #include "net/ssl/test_ssl_private_key.h"
14 #include "third_party/boringssl/src/include/openssl/bio.h"
15 #include "third_party/boringssl/src/include/openssl/evp.h"
16 #include "third_party/boringssl/src/include/openssl/pem.h"
17 
18 namespace net::key_util {
19 
LoadEVP_PKEYFromPEM(const base::FilePath & filepath)20 bssl::UniquePtr<EVP_PKEY> LoadEVP_PKEYFromPEM(const base::FilePath& filepath) {
21   std::string data;
22   if (!base::ReadFileToString(filepath, &data)) {
23     LOG(ERROR) << "Could not read private key file: " << filepath.value();
24     return nullptr;
25   }
26   bssl::UniquePtr<BIO> bio(BIO_new_mem_buf(const_cast<char*>(data.data()),
27                                            static_cast<int>(data.size())));
28   if (!bio) {
29     LOG(ERROR) << "Could not allocate BIO for buffer?";
30     return nullptr;
31   }
32   bssl::UniquePtr<EVP_PKEY> result(
33       PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
34   if (!result) {
35     LOG(ERROR) << "Could not decode private key file: " << filepath.value();
36     return nullptr;
37   }
38   return result;
39 }
40 
PEMFromPrivateKey(EVP_PKEY * key)41 std::string PEMFromPrivateKey(EVP_PKEY* key) {
42   bssl::UniquePtr<BIO> temp_memory_bio(BIO_new(BIO_s_mem()));
43   if (!temp_memory_bio) {
44     LOG(ERROR) << "Failed to allocate temporary memory bio";
45     return std::string();
46   }
47   if (!PEM_write_bio_PrivateKey(temp_memory_bio.get(), key, nullptr, nullptr, 0,
48                                 nullptr, nullptr)) {
49     LOG(ERROR) << "Failed to write private key";
50     return std::string();
51   }
52   const uint8_t* buffer;
53   size_t len;
54   if (!BIO_mem_contents(temp_memory_bio.get(), &buffer, &len)) {
55     LOG(ERROR) << "BIO_mem_contents failed";
56     return std::string();
57   }
58   return std::string(reinterpret_cast<const char*>(buffer), len);
59 }
60 
LoadPrivateKeyOpenSSL(const base::FilePath & filepath)61 scoped_refptr<SSLPrivateKey> LoadPrivateKeyOpenSSL(
62     const base::FilePath& filepath) {
63   bssl::UniquePtr<EVP_PKEY> key = LoadEVP_PKEYFromPEM(filepath);
64   if (!key)
65     return nullptr;
66   return WrapOpenSSLPrivateKey(std::move(key));
67 }
68 
69 }  // namespace net::key_util
70