From 2da5097b23cf16b1fd2933cb8ec8def0db104373 Mon Sep 17 00:00:00 2001 From: pajama-coder Date: Fri, 10 Jan 2025 10:44:14 +0800 Subject: [PATCH] [api] Option to load keys as usual when using OpenSSL engine --- src/api/crypto.cpp | 28 ++++++++-------------------- src/main.cpp | 1 + 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/src/api/crypto.cpp b/src/api/crypto.cpp index fc7c3a24..a8f62698 100644 --- a/src/api/crypto.cpp +++ b/src/api/crypto.cpp @@ -78,6 +78,8 @@ auto Crypto::get_openssl_engine() -> ENGINE* { } void Crypto::init(const std::string &engine_id) { + OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, nullptr); + if (!engine_id.empty()) { ENGINE_load_builtin_engines(); @@ -150,12 +152,8 @@ PublicKey::PublicKey(EVP_PKEY *pkey) : m_pkey(pkey) { PublicKey::PublicKey(Data *data) { if (!data->size()) throw std::runtime_error("Data size is zero"); - if (s_openssl_engine) { - m_pkey = load_by_engine(data->to_string()); - } else { - auto buf = data->to_bytes(); - m_pkey = read_pem(&buf[0], buf.size()); - } + auto buf = data->to_bytes(); + m_pkey = read_pem(&buf[0], buf.size()); } PublicKey::PublicKey(pjs::Str *data) { @@ -203,10 +201,7 @@ auto PublicKey::read_pem(const void *data, size_t size) -> EVP_PKEY* { auto PublicKey::load_by_engine(const std::string &id) -> EVP_PKEY* { auto pkey = ENGINE_load_public_key(s_openssl_engine, id.c_str(), nullptr, nullptr); - if (!pkey) { - std::string msg("cannot load public key from OpenSSL engine: "); - throw std::runtime_error(msg + id); - } + if (!pkey) throw_error(); EVP_PKEY_set1_engine(pkey, s_openssl_engine); return pkey; } @@ -226,12 +221,8 @@ PrivateKey::GenerateOptions::GenerateOptions(pjs::Object *options) { PrivateKey::PrivateKey(Data *data) { if (!data->size()) throw std::runtime_error("Data size is zero"); - if (s_openssl_engine) { - m_pkey = load_by_engine(data->to_string()); - } else { - auto buf = data->to_bytes(); - m_pkey = read_pem(&buf[0], buf.size()); - } + auto buf = data->to_bytes(); + m_pkey = read_pem(&buf[0], buf.size()); } PrivateKey::PrivateKey(pjs::Str *data) { @@ -308,10 +299,7 @@ auto PrivateKey::read_pem(const void *data, size_t size) -> EVP_PKEY* { auto PrivateKey::load_by_engine(const std::string &id) -> EVP_PKEY* { auto pkey = ENGINE_load_private_key(s_openssl_engine, id.c_str(), nullptr, nullptr); - if (!pkey) { - std::string msg("cannot load private key from OpenSSL engine: "); - throw std::runtime_error(msg + id); - } + if (!pkey) throw_error(); EVP_PKEY_set1_engine(pkey, s_openssl_engine); return pkey; } diff --git a/src/main.cpp b/src/main.cpp index 9a5286eb..4a282782 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -79,6 +79,7 @@ static void show_version() { std::cout << "Tongsuo : " << TONGSUO_VERSION_TEXT << std::endl; #else std::cout << "OpenSSL : " << OPENSSL_VERSION_TEXT << std::endl; + std::cout << "OpenSSL Conf : " << CONF_get1_default_config_file() << std::endl; #endif #ifdef PIPY_USE_GUI