blob: a84c43b6bd8194d3c7f45d889db6199546b170e4 [file] [log] [blame]
Taylor Brandstetter165c6182020-12-10 16:23:03 -08001/*
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 "rtc_base/checks.h"
20#include "rtc_base/constructor_magic.h"
21#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(
38 const std::string& pem_string);
39
40 ~OpenSSLKeyPair();
41
42 std::unique_ptr<OpenSSLKeyPair> Clone();
43
44 EVP_PKEY* pkey() const { return pkey_; }
45 std::string PrivateKeyToPEMString() const;
46 std::string PublicKeyToPEMString() const;
47 bool operator==(const OpenSSLKeyPair& other) const;
48 bool operator!=(const OpenSSLKeyPair& other) const;
49
50 private:
51 void AddReference();
52
53 EVP_PKEY* pkey_;
54
55 RTC_DISALLOW_COPY_AND_ASSIGN(OpenSSLKeyPair);
56};
57
58} // namespace rtc
59
60#endif // RTC_BASE_OPENSSL_KEY_PAIR_H_