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 #ifndef UTIL_CRYPTO_CERTIFICATE_UTILS_H_ 6 #define UTIL_CRYPTO_CERTIFICATE_UTILS_H_ 7 8 #include <openssl/evp.h> 9 #include <openssl/x509.h> 10 #include <stdint.h> 11 12 #include <chrono> 13 #include <string> 14 #include <vector> 15 16 #include "absl/strings/string_view.h" 17 #include "platform/api/time.h" 18 #include "platform/base/error.h" 19 #include "util/crypto/rsa_private_key.h" 20 21 namespace openscreen { 22 23 // Generates a new RSA key pair with bit width |key_bits|. 24 bssl::UniquePtr<EVP_PKEY> GenerateRsaKeyPair(int key_bits = 2048); 25 26 // Creates a new X509 certificate having the given |name| and |duration| until 27 // expiration, and based on the given |key_pair|. If |issuer| and |issuer_key| 28 // are provided, they are used to set the issuer information, otherwise it will 29 // be self-signed. |make_ca| determines whether additional extensions are added 30 // to make it a valid certificate authority cert. 31 ErrorOr<bssl::UniquePtr<X509>> CreateSelfSignedX509Certificate( 32 absl::string_view name, 33 std::chrono::seconds duration, 34 const EVP_PKEY& key_pair, 35 std::chrono::seconds time_since_unix_epoch = GetWallTimeSinceUnixEpoch(), 36 bool make_ca = false, 37 X509* issuer = nullptr, 38 EVP_PKEY* issuer_key = nullptr); 39 40 // Exports the given X509 certificate as its DER-encoded binary form. 41 ErrorOr<std::vector<uint8_t>> ExportX509CertificateToDer( 42 const X509& certificate); 43 44 // Parses a DER-encoded X509 certificate from its binary form. 45 ErrorOr<bssl::UniquePtr<X509>> ImportCertificate(const uint8_t* der_x509_cert, 46 int der_x509_cert_length); 47 48 // Parses a DER-encoded RSAPrivateKey (RFC 3447). 49 ErrorOr<bssl::UniquePtr<EVP_PKEY>> ImportRSAPrivateKey( 50 const uint8_t* der_rsa_private_key, 51 int key_length); 52 53 std::string GetSpkiTlv(X509* cert); 54 55 ErrorOr<uint64_t> ParseDerUint64(const ASN1_INTEGER* asn1int); 56 57 } // namespace openscreen 58 59 #endif // UTIL_CRYPTO_CERTIFICATE_UTILS_H_ 60