From ac9d7942ce6c446c711b21787d1d18c47d88ff59 Mon Sep 17 00:00:00 2001 From: Moreno Giussani <giussani.moreno@gmail.com> Date: Thu, 9 Feb 2023 15:11:13 +0100 Subject: [PATCH] Add loadIdentity --- include/opendht/crypto.h | 1 + src/crypto.cpp | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/include/opendht/crypto.h b/include/opendht/crypto.h index d811cfb7..1033c04d 100644 --- a/include/opendht/crypto.h +++ b/include/opendht/crypto.h @@ -772,6 +772,7 @@ OPENDHT_PUBLIC Identity generateEcIdentity(const std::string& name, const Identi OPENDHT_PUBLIC Identity generateEcIdentity(const std::string& name = "dhtnode", const Identity& ca = {}); OPENDHT_PUBLIC void saveIdentity(const Identity& id, const std::string& path, const std::string& privkey_password = {}); +OPENDHT_PUBLIC Identity loadIdentity(const std::string &path,const std::string &privkey_password = {}); /** * Performs SHA512, SHA256 or SHA1, depending on hash_length. diff --git a/src/crypto.cpp b/src/crypto.cpp index d5041911..578003e2 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -1132,6 +1132,26 @@ saveIdentity(const Identity& id, const std::string& path, const std::string& pri } } +Identity +loadIdentity(const std::string &path,const std::string &privkey_password) +{ + std::ifstream pkStream(path + ".pem", std::ios::in | std::ios::binary); + std::vector<uint8_t> pkContent((std::istreambuf_iterator<char>(pkStream)), + std::istreambuf_iterator<char>()); + auto key = std::make_shared<PrivateKey>(pkContent, privkey_password); + pkStream.close(); + // Create a certificate + gnutls_x509_crt_t gnuCert; + if (gnutls_x509_crt_init(&gnuCert) != GNUTLS_E_SUCCESS) + throw std::runtime_error("Failed to initialize gnutls certificate struct"); + gnutls_datum_t crtContent; + // Read the certificate file + gnutls_load_file((path + ".crt").c_str(), &crtContent); + gnutls_x509_crt_import(gnuCert, &crtContent, GNUTLS_X509_FMT_PEM); + auto cert = std::make_shared<Certificate>(gnuCert); + return {std::move(key), std::move(cert)}; +} + void setValidityPeriod(gnutls_x509_crt_t cert, int64_t validity) { -- GitLab