diff --git a/include/opendht/crypto.h b/include/opendht/crypto.h index d811cfb7ad66f9903f2b5ac49cf1f8ada60dbef6..1033c04d99909885f1f225f2594f4597241d7727 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 d504191169fa74e7c68d92f83c387483d996b404..578003e2882f0ecb38f3fa5ab0385cda6def9138 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) {