1 // Copyright 2024 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/ssl/openssl_private_key.h"
6
7 #include <string>
8
9 #include "base/files/file_path.h"
10 #include "base/files/file_util.h"
11 #include "crypto/openssl_util.h"
12 #include "net/ssl/ssl_private_key.h"
13 #include "net/ssl/ssl_private_key_test_util.h"
14 #include "net/test/cert_test_util.h"
15 #include "net/test/test_data_directory.h"
16 #include "net/test/test_with_task_environment.h"
17 #include "testing/gtest/include/gtest/gtest.h"
18 #include "third_party/boringssl/src/include/openssl/bytestring.h"
19 #include "third_party/boringssl/src/include/openssl/evp.h"
20
21 namespace net {
22
23 namespace {
24
25 struct TestKey {
26 const char* name;
27 const char* cert_file;
28 const char* key_file;
29 int type;
30 };
31
32 const TestKey kTestKeys[] = {
33 {"RSA", "client_1.pem", "client_1.pk8", EVP_PKEY_RSA},
34 {"ECDSA_P256", "client_4.pem", "client_4.pk8", EVP_PKEY_EC},
35 {"ECDSA_P384", "client_5.pem", "client_5.pk8", EVP_PKEY_EC},
36 {"ECDSA_P521", "client_6.pem", "client_6.pk8", EVP_PKEY_EC},
37 };
38
TestKeyToString(const testing::TestParamInfo<TestKey> & params)39 std::string TestKeyToString(const testing::TestParamInfo<TestKey>& params) {
40 return params.param.name;
41 }
42
43 } // namespace
44
45 class OpenSSLPrivateKeyTest : public testing::TestWithParam<TestKey>,
46 public WithTaskEnvironment {};
47
TEST_P(OpenSSLPrivateKeyTest,KeyMatches)48 TEST_P(OpenSSLPrivateKeyTest, KeyMatches) {
49 const TestKey& test_key = GetParam();
50
51 std::string pkcs8;
52 base::FilePath pkcs8_path =
53 GetTestCertsDirectory().AppendASCII(test_key.key_file);
54 ASSERT_TRUE(base::ReadFileToString(pkcs8_path, &pkcs8));
55
56 // Create an EVP_PKEY from the PKCS#8 buffer.
57 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
58 CBS cbs;
59 CBS_init(&cbs, reinterpret_cast<const uint8_t*>(pkcs8.data()), pkcs8.size());
60 bssl::UniquePtr<EVP_PKEY> openssl_key(EVP_parse_private_key(&cbs));
61 ASSERT_TRUE(openssl_key);
62 EXPECT_EQ(0u, CBS_len(&cbs));
63
64 scoped_refptr<SSLPrivateKey> private_key =
65 WrapOpenSSLPrivateKey(std::move(openssl_key));
66 ASSERT_TRUE(private_key);
67 net::TestSSLPrivateKeyMatches(private_key.get(), pkcs8);
68 }
69
70 INSTANTIATE_TEST_SUITE_P(All,
71 OpenSSLPrivateKeyTest,
72 testing::ValuesIn(kTestKeys),
73 TestKeyToString);
74
75 } // namespace net
76