• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
5 #include "util/crypto/certificate_utils.h"
6 
7 #include <openssl/bio.h>
8 #include <openssl/bn.h>
9 #include <openssl/rsa.h>
10 #include <openssl/x509.h>
11 
12 #include <chrono>
13 
14 #include "gtest/gtest.h"
15 #include "platform/api/time.h"
16 #include "platform/base/error.h"
17 #include "util/std_util.h"
18 
19 namespace openscreen {
20 namespace {
21 
22 constexpr char kName[] = "test.com";
23 constexpr auto kDuration = std::chrono::seconds(31556952);
24 
TEST(CertificateUtilTest,CreatesValidCertificate)25 TEST(CertificateUtilTest, CreatesValidCertificate) {
26   bssl::UniquePtr<EVP_PKEY> pkey = GenerateRsaKeyPair();
27   ASSERT_TRUE(pkey);
28 
29   ErrorOr<bssl::UniquePtr<X509>> certificate =
30       CreateSelfSignedX509Certificate(kName, kDuration, *pkey);
31   ASSERT_TRUE(certificate.is_value());
32 
33   // Validate the generated certificate.
34   EXPECT_NE(0, X509_verify(certificate.value().get(), pkey.get()));
35 }
36 
TEST(CertificateUtilTest,ExportsAndImportsCertificate)37 TEST(CertificateUtilTest, ExportsAndImportsCertificate) {
38   bssl::UniquePtr<EVP_PKEY> pkey = GenerateRsaKeyPair();
39   ASSERT_TRUE(pkey);
40   ErrorOr<bssl::UniquePtr<X509>> certificate =
41       CreateSelfSignedX509Certificate(kName, kDuration, *pkey);
42   ASSERT_TRUE(certificate.is_value());
43 
44   ErrorOr<std::vector<uint8_t>> exported =
45       ExportX509CertificateToDer(*certificate.value());
46   ASSERT_TRUE(exported.is_value()) << exported.error();
47   EXPECT_FALSE(exported.value().empty());
48 
49   ErrorOr<bssl::UniquePtr<X509>> imported =
50       ImportCertificate(exported.value().data(), exported.value().size());
51   ASSERT_TRUE(imported.is_value()) << imported.error();
52   ASSERT_TRUE(imported.value().get());
53 
54   // Validate the imported certificate.
55   EXPECT_NE(0, X509_verify(imported.value().get(), pkey.get()));
56 }
57 
58 }  // namespace
59 }  // namespace openscreen
60