xbot/myirc/openssl_utils.cpp

72 lines
1.8 KiB
C++
Raw Normal View History

2025-02-01 11:04:33 -08:00
#include "myirc/openssl_utils.hpp"
2025-01-29 18:41:28 -08:00
2025-02-01 11:04:33 -08:00
#include "myirc/c_callback.hpp"
2025-01-29 18:41:28 -08:00
#include <openssl/err.h>
#include <openssl/pem.h>
#include <boost/log/trivial.hpp>
#include <cstdio>
using namespace std::literals;
2025-02-01 11:04:33 -08:00
namespace myirc {
2025-01-29 18:41:28 -08:00
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);
}
2025-01-30 11:47:26 -08:00
auto cert_from_file(const std::string &filename) -> Ref<X509>
2025-01-29 18:41:28 -08:00
{
2025-01-30 11:47:26 -08:00
Ref<X509> cert;
2025-01-29 18:41:28 -08:00
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;
}
2025-01-30 11:47:26 -08:00
auto key_from_file(const std::string &filename, const std::string_view password) -> Ref<EVP_PKEY>
2025-01-29 18:41:28 -08:00
{
2025-01-30 11:47:26 -08:00
Ref<EVP_PKEY> key;
2025-01-29 18:41:28 -08:00
if (const auto fp = fopen(filename.c_str(), "r"))
{
auto cb = [password](char * const buf, int const size, int) -> int {
2025-02-05 09:24:47 -08:00
if (std::cmp_less(size, password.size())) { return -1; }
2025-01-29 18:41:28 -08:00
std::copy(password.begin(), password.end(), buf);
2025-02-05 09:24:47 -08:00
return static_cast<int>(password.size());
2025-01-29 18:41:28 -08:00
};
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;
}
2025-02-01 11:04:33 -08:00
} // namespace myirc