blob: d09bdb0d5efba1a653721e7a13de78c2d2d946e4 [file] [log] [blame]
Taylor Brandstetter165c6182020-12-11 00:23:031/*
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 Tofigh7fa90572022-03-17 14:47:4919#include "absl/strings/string_view.h"
Taylor Brandstetter165c6182020-12-11 00:23:0320#include "rtc_base/checks.h"
Taylor Brandstetter165c6182020-12-11 00:23:0321#include "rtc_base/ssl_identity.h"
22
23namespace rtc {
24
25// OpenSSLKeyPair encapsulates an OpenSSL EVP_PKEY* keypair object,
26// which is reference counted inside the OpenSSL library.
27class 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 Tofigh7fa90572022-03-17 14:47:4938 absl::string_view pem_string);
Taylor Brandstetter165c6182020-12-11 00:23:0339
40 ~OpenSSLKeyPair();
41
Byoungchan Lee14af7622022-01-11 20:24:5842 OpenSSLKeyPair(const OpenSSLKeyPair&) = delete;
43 OpenSSLKeyPair& operator=(const OpenSSLKeyPair&) = delete;
44
Taylor Brandstetter165c6182020-12-11 00:23:0345 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 Brandstetter165c6182020-12-11 00:23:0357};
58
59} // namespace rtc
60
61#endif // RTC_BASE_OPENSSL_KEY_PAIR_H_