Avi Drissman | 6459548 | 2022-09-14 20:52:29 | [diff] [blame^] | 1 | // Copyright 2019 The Chromium Authors |
Jesse Selover | 1d82faf | 2019-03-20 19:44:35 | [diff] [blame] | 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 | |
Tsuyoshi Horo | 4f516be | 2022-06-14 11:53:13 | [diff] [blame] | 18 | namespace net::key_util { |
Jesse Selover | 1d82faf | 2019-03-20 19:44:35 | [diff] [blame] | 19 | |
| 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 | |
| 41 | scoped_refptr<SSLPrivateKey> LoadPrivateKeyOpenSSL( |
| 42 | const base::FilePath& filepath) { |
| 43 | bssl::UniquePtr<EVP_PKEY> key = LoadEVP_PKEYFromPEM(filepath); |
| 44 | if (!key) |
| 45 | return nullptr; |
| 46 | return WrapOpenSSLPrivateKey(std::move(key)); |
| 47 | } |
| 48 | |
Tsuyoshi Horo | 4f516be | 2022-06-14 11:53:13 | [diff] [blame] | 49 | } // namespace net::key_util |