diff --git a/openssl_utils.cpp b/openssl_utils.cpp new file mode 100644 index 0000000..3dee2c9 --- /dev/null +++ b/openssl_utils.cpp @@ -0,0 +1,67 @@ +#include "openssl_utils.hpp" + +#include "c_callback.hpp" + +#include +#include + +#include + +#include + +using namespace std::literals; + +auto log_openssl_errors(const std::string_view prefix) -> void +{ + auto err_cb = [prefix](const char *str, size_t len) -> int { + BOOST_LOG_TRIVIAL(error) << prefix << std::string_view{str, len}; + return 0; + }; + ERR_print_errors_cb(CCallback::invoke, &err_cb); +} + +auto cert_from_file(const std::string &filename) -> X509_Ref +{ + X509_Ref cert; + if (const auto fp = fopen(filename.c_str(), "r")) + { + cert.reset(PEM_read_X509(fp, nullptr, nullptr, nullptr)); + if (cert.get() == nullptr) + { + log_openssl_errors("Reading certificate: "sv); + } + fclose(fp); + } + else + { + const auto err = strerror(errno); + BOOST_LOG_TRIVIAL(error) << "Opening certificate: " << err; + } + return cert; +} + +auto key_from_file(const std::string &filename, const std::string_view password) -> EVP_PKEY_Ref +{ + EVP_PKEY_Ref key; + if (const auto fp = fopen(filename.c_str(), "r")) + { + auto cb = [password](char * const buf, int const size, int) -> int { + if (size < password.size()) { return -1; } + std::copy(password.begin(), password.end(), buf); + return password.size(); + }; + + key.reset(PEM_read_PrivateKey(fp, nullptr, CCallback::invoke, &cb)); + if (key.get() == nullptr) + { + log_openssl_errors("Reading private key: "sv); + } + fclose(fp); + } + else + { + const auto err = strerror(errno); + BOOST_LOG_TRIVIAL(error) << "Opening private key: " << err; + } + return key; +} diff --git a/openssl_utils.hpp b/openssl_utils.hpp new file mode 100644 index 0000000..65c5d01 --- /dev/null +++ b/openssl_utils.hpp @@ -0,0 +1,9 @@ +#pragma once + +#include "ref.hpp" + +#include + +auto log_openssl_errors(const std::string_view prefix) -> void; +auto key_from_file(const std::string &filename, const std::string_view password) -> EVP_PKEY_Ref; +auto cert_from_file(const std::string &filename) -> X509_Ref;