Amna | 423b25b | 2024-02-06 13:21:19 -0500 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2023 Savoir-faire Linux Inc. |
| 3 | * |
| 4 | * This program is free software: you can redistribute it and/or modify |
| 5 | * it under the terms of the GNU General Public License as published by |
| 6 | * the Free Software Foundation, either version 3 of the License, or |
| 7 | * (at your option) any later version. |
| 8 | * |
| 9 | * This program is distributed in the hope that it will be useful, |
| 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | * GNU General Public License for more details. |
| 13 | * |
| 14 | * You should have received a copy of the GNU General Public License |
| 15 | * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | */ |
| 17 | |
| 18 | #include "dhtnet_crtmgr.h" |
| 19 | #include "fileutils.h" |
| 20 | |
| 21 | #include <opendht/crypto.h> |
| 22 | |
| 23 | |
| 24 | namespace dhtnet { |
| 25 | |
| 26 | dht::crypto::Identity |
| 27 | loadIdentity(const std::filesystem::path& privatekey, const std::filesystem::path& cert) |
| 28 | { |
| 29 | // check files exists |
| 30 | if (!std::filesystem::exists(privatekey) or !std::filesystem::exists(cert)) |
| 31 | { |
| 32 | fmt::print(stderr, "Error: missing identity files\n"); |
| 33 | return {}; |
| 34 | } |
| 35 | |
| 36 | // Load identity |
| 37 | auto privateKey = std::make_unique<dht::crypto::PrivateKey>(fileutils::loadFile(privatekey)); |
| 38 | auto certificate = std::make_unique<dht::crypto::Certificate>(fileutils::loadFile(cert)); |
| 39 | return dht::crypto::Identity(std::move(privateKey), std::move(certificate)); |
| 40 | } |
| 41 | |
| 42 | // generate a new identity |
| 43 | dht::crypto::Identity generateIdentity(const std::filesystem::path& path_id, const std::string& name, const dht::crypto::Identity& ca) |
| 44 | { |
| 45 | auto identity = dht::crypto::generateIdentity(name, ca); |
Amna | c835404 | 2024-07-24 15:31:32 -0400 | [diff] [blame] | 46 | std::error_code ec; |
| 47 | std::filesystem::create_directories(path_id, ec); |
| 48 | if (ec) { |
| 49 | fmt::print(stderr, "Error: failed to create directory {}\n", path_id.string()); |
| 50 | return {}; |
| 51 | } |
Amna | 084d8a3 | 2024-08-14 10:24:56 -0400 | [diff] [blame] | 52 | // catch error |
| 53 | try{ |
| 54 | dht::crypto::saveIdentity(identity, path_id / name); |
| 55 | } catch (const std::exception& e) { |
| 56 | fmt::print(stderr, "Error: failed to save identity: {}\n", e.what()); |
| 57 | return {}; |
| 58 | } |
Amna | 423b25b | 2024-02-06 13:21:19 -0500 | [diff] [blame] | 59 | return identity; |
| 60 | } |
| 61 | } // namespace dhtnet |