openssl utils
This commit is contained in:
parent
5f32505b93
commit
8d544e31de
67
openssl_utils.cpp
Normal file
67
openssl_utils.cpp
Normal file
@ -0,0 +1,67 @@
|
||||
#include "openssl_utils.hpp"
|
||||
|
||||
#include "c_callback.hpp"
|
||||
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/pem.h>
|
||||
|
||||
#include <boost/log/trivial.hpp>
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
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<decltype(err_cb)>::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<decltype(cb)>::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;
|
||||
}
|
9
openssl_utils.hpp
Normal file
9
openssl_utils.hpp
Normal file
@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include "ref.hpp"
|
||||
|
||||
#include <string_view>
|
||||
|
||||
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;
|
Loading…
x
Reference in New Issue
Block a user