OpenVPN 3 Core Library
Loading...
Searching...
No Matches
dh.hpp
Go to the documentation of this file.
1// OpenVPN -- An application to securely tunnel IP networks
2// over a single port, with support for SSL/TLS-based
3// session authentication and key exchange,
4// packet encryption, packet authentication, and
5// packet compression.
6//
7// Copyright (C) 2012- OpenVPN Inc.
8//
9// SPDX-License-Identifier: MPL-2.0 OR AGPL-3.0-only WITH openvpn3-openssl-exception
10//
11
12// Wrap an OpenSSL DH object
13
14#pragma once
15
16#include <string>
17
18
23
24#if OPENSSL_VERSION_NUMBER < 0x30000000L
26#else
27
28
29namespace openvpn::OpenSSLPKI {
30
31
32
33class DH
34{
35 public:
36 DH()
37 : dh_(nullptr)
38 {
39 }
40
41 explicit DH(const std::string &dh_txt)
42 : dh_(nullptr)
43 {
44 parse_pem(dh_txt);
45 }
46
47 DH(const DH &other)
48 {
49 dup(other.dh_);
50 }
51
52 DH(DH &&other) noexcept
53 : dh_(other.dh_)
54 {
55 other.dh_ = nullptr;
56 }
57
58 void operator=(const DH &other)
59 {
60 if (this != &other)
61 {
62 erase();
63 dup(other.dh_);
64 }
65 }
66
67 DH &operator=(DH &&other) noexcept
68 {
69 if (this != &other)
70 {
71 erase();
72 dh_ = other.dh_;
73 other.dh_ = nullptr;
74 }
75 return *this;
76 }
77
78 bool defined() const
79 {
80 return dh_ != nullptr;
81 }
82 ::EVP_PKEY *obj() const
83 {
84 return dh_;
85 }
86
92 ::EVP_PKEY *obj_release()
93 {
94 auto dh = dh_;
95 dh_ = nullptr;
96 return dh;
97 }
98
99 void parse_pem(const std::string &dh_txt)
100 {
101 BIO *bio = ::BIO_new_mem_buf(const_cast<char *>(dh_txt.c_str()), numeric_cast<int>(dh_txt.length()));
102 if (!bio)
103 throw OpenSSLException();
104
105 ::EVP_PKEY *dh = ::PEM_read_bio_Parameters_ex(bio, nullptr, nullptr, nullptr);
106 ::BIO_free(bio);
107 if (!dh)
108 throw OpenSSLException("DH::parse_pem");
109
110 erase();
111 dh_ = dh;
112 }
113
114 std::string render_pem() const
115 {
116 if (dh_)
117 {
118 BIO *bio = ::BIO_new(BIO_s_mem());
119 const int ret = ::PEM_write_bio_Parameters(bio, dh_);
120 if (ret == 0)
121 {
122 ::BIO_free(bio);
123 throw OpenSSLException("DH::render_pem");
124 }
125
126 {
127 char *temp;
128 const size_t buf_len = ::BIO_get_mem_data(bio, &temp);
129 std::string ret = std::string(temp, buf_len);
130 ::BIO_free(bio);
131 return ret;
132 }
133 }
134 else
135 return "";
136 }
137
138 ~DH()
139 {
140 erase();
141 }
142
143 private:
144 void erase()
145 {
146 if (dh_)
147 ::EVP_PKEY_free(dh_);
148 }
149
150 void dup(const ::EVP_PKEY *dh)
151 {
152 if (dh)
153 dh_ = EVP_PKEY_dup(const_cast<EVP_PKEY *>(dh));
154 else
155 dh_ = nullptr;
156 }
157
158 ::EVP_PKEY *dh_;
159};
160} // namespace openvpn::OpenSSLPKI
161#endif
void parse_pem(const std::string &dh_txt)
void dup(const ::DH *dh)
void operator=(const DH &other)
Definition dh-compat.hpp:71
std::string render_pem() const
std::string ret