diff --git a/include/opendht/crypto.h b/include/opendht/crypto.h index f26a65f2a..fc74a923f 100644 --- a/include/opendht/crypto.h +++ b/include/opendht/crypto.h @@ -764,6 +764,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 dba347320..5e8aa18b2 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -1122,6 +1122,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 pkContent((std::istreambuf_iterator(pkStream)), + std::istreambuf_iterator()); + auto key = std::make_shared(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(gnuCert); + return {std::move(key), std::move(cert)}; +} + void setValidityPeriod(gnutls_x509_crt_t cert, int64_t validity) {