Taylor Brandstetter | 165c618 | 2020-12-11 00:23:03 | [diff] [blame] | 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 | |
Ali Tofigh | 7fa9057 | 2022-03-17 14:47:49 | [diff] [blame] | 19 | #include "absl/strings/string_view.h" |
Taylor Brandstetter | 165c618 | 2020-12-11 00:23:03 | [diff] [blame] | 20 | #include "rtc_base/checks.h" |
Taylor Brandstetter | 165c618 | 2020-12-11 00:23:03 | [diff] [blame] | 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. |
| 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( |
Ali Tofigh | 7fa9057 | 2022-03-17 14:47:49 | [diff] [blame] | 38 | absl::string_view pem_string); |
Taylor Brandstetter | 165c618 | 2020-12-11 00:23:03 | [diff] [blame] | 39 | |
| 40 | ~OpenSSLKeyPair(); |
| 41 | |
Byoungchan Lee | 14af762 | 2022-01-11 20:24:58 | [diff] [blame] | 42 | OpenSSLKeyPair(const OpenSSLKeyPair&) = delete; |
| 43 | OpenSSLKeyPair& operator=(const OpenSSLKeyPair&) = delete; |
| 44 | |
Taylor Brandstetter | 165c618 | 2020-12-11 00:23:03 | [diff] [blame] | 45 | std::unique_ptr<OpenSSLKeyPair> Clone(); |
| 46 | |
| 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_; |
Taylor Brandstetter | 165c618 | 2020-12-11 00:23:03 | [diff] [blame] | 57 | }; |
| 58 | |
| 59 | } // namespace rtc |
| 60 | |
| 61 | #endif // RTC_BASE_OPENSSL_KEY_PAIR_H_ |