userver: userver/crypto/private_key.hpp Source File
Loading...
Searching...
No Matches
private_key.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/crypto/private_key.hpp
4/// @brief @copybrief crypto::PrivateKey
5
6#include <memory>
7#include <optional>
8#include <string>
9#include <string_view>
10
11#include <userver/crypto/basic_types.hpp>
12
13USERVER_NAMESPACE_BEGIN
14
15namespace crypto {
16
17/// @ingroup userver_universal userver_containers
18///
19/// Loaded into memory private key
21public:
22 using NativeType = EVP_PKEY;
23
24 PrivateKey() = default;
25
26 NativeType* GetNative() const noexcept { return pkey_.get(); }
27 explicit operator bool() const noexcept { return !!pkey_; }
28
29 /// Returns a PEM-encoded representation of stored private key encrypted by
30 /// the provided password.
31 ///
32 /// @throw crypto::SerializationError if the password is empty or
33 /// serialization fails.
34 std::optional<std::string> GetPemString(std::string_view password) const;
35
36 /// Returns a PEM-encoded representation of stored private key in an
37 /// unencrypted form.
38 ///
39 /// @throw crypto::SerializationError if serialization fails.
40 std::optional<std::string> GetPemStringUnencrypted() const;
41
42 /// Accepts a string that contains a private key and a password, checks the
43 /// key and password, loads it into OpenSSL structures and returns as a
44 /// PrivateKey variable.
45 ///
46 /// @throw crypto::KeyParseError if failed to load the key.
47 static PrivateKey LoadFromString(std::string_view key, std::string_view password);
48
49 /// Accepts a string that contains a private key (not protected with
50 /// password), checks the key and password, loads it into OpenSSL structures
51 /// and returns as a PrivateKey variable.
52 ///
53 /// @throw crypto::KeyParseError if failed to load the key.
54 static PrivateKey LoadFromString(std::string_view key);
55
56private:
57 explicit PrivateKey(std::shared_ptr<NativeType> pkey) : pkey_(std::move(pkey)) {}
58
59 std::shared_ptr<NativeType> pkey_{};
60};
61
62} // namespace crypto
63
64USERVER_NAMESPACE_END