1 /* 2 * Copyright 2020 The WebRTC Project Authors. All rights reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 11 #ifndef RTC_BASE_OPENSSL_KEY_PAIR_H_ 12 #define RTC_BASE_OPENSSL_KEY_PAIR_H_ 13 14 #include <openssl/ossl_typ.h> 15 16 #include <memory> 17 #include <string> 18 19 #include "absl/strings/string_view.h" 20 #include "rtc_base/checks.h" 21 #include "rtc_base/ssl_identity.h" 22 23 namespace rtc { 24 25 // OpenSSLKeyPair encapsulates an OpenSSL EVP_PKEY* keypair object, 26 // which is reference counted inside the OpenSSL library. 27 class OpenSSLKeyPair final { 28 public: 29 // Takes ownership of the key. OpenSSLKeyPair(EVP_PKEY * pkey)30 explicit OpenSSLKeyPair(EVP_PKEY* pkey) : pkey_(pkey) { 31 RTC_DCHECK(pkey_ != nullptr); 32 } 33 34 static std::unique_ptr<OpenSSLKeyPair> Generate(const KeyParams& key_params); 35 // Constructs a key pair from the private key PEM string. This must not result 36 // in missing public key parameters. Returns null on error. 37 static std::unique_ptr<OpenSSLKeyPair> FromPrivateKeyPEMString( 38 absl::string_view pem_string); 39 40 ~OpenSSLKeyPair(); 41 42 OpenSSLKeyPair(const OpenSSLKeyPair&) = delete; 43 OpenSSLKeyPair& operator=(const OpenSSLKeyPair&) = delete; 44 45 std::unique_ptr<OpenSSLKeyPair> Clone(); 46 pkey()47 EVP_PKEY* pkey() const { return pkey_; } 48 std::string PrivateKeyToPEMString() const; 49 std::string PublicKeyToPEMString() const; 50 bool operator==(const OpenSSLKeyPair& other) const; 51 bool operator!=(const OpenSSLKeyPair& other) const; 52 53 private: 54 void AddReference(); 55 56 EVP_PKEY* pkey_; 57 }; 58 59 } // namespace rtc 60 61 #endif // RTC_BASE_OPENSSL_KEY_PAIR_H_ 62