011-tls-util.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. // SPDX-FileCopyrightText: 2019-2025 Ivan Baidakou
  3. #include "test-utils.h"
  4. #include "utils/base32.h"
  5. #include "utils/tls.h"
  6. #include <openssl/pem.h>
  7. #include <filesystem>
  8. #include <cstdio>
  9. using namespace syncspirit::utils;
  10. using namespace syncspirit::test;
  11. namespace bfs = std::filesystem;
  12. TEST_CASE("generate cert/key pair, save & load", "[support][tls]") {
  13. auto pair = generate_pair("sample");
  14. REQUIRE((bool)pair);
  15. REQUIRE((bool)pair.value().cert);
  16. REQUIRE((bool)pair.value().private_key);
  17. REQUIRE(pair.value().cert_data.bytes.size() > 0);
  18. auto &value = pair.value();
  19. PEM_write_PrivateKey(stdout, value.private_key.get(), nullptr, nullptr, 0, nullptr, nullptr);
  20. PEM_write_X509(stdout, value.cert.get());
  21. X509_print_fp(stdout, value.cert.get());
  22. auto cert_file = unique_path();
  23. auto cert_file_path = cert_file.string();
  24. auto cert_file_guard = path_guard_t(cert_file);
  25. auto key_file = unique_path();
  26. auto key_file_path = key_file.string();
  27. auto key_file_guard = path_guard_t(key_file);
  28. auto save_result = value.save(cert_file_path.c_str(), key_file_path.c_str());
  29. REQUIRE((bool)save_result);
  30. printf("cert has been saved as %s\n", cert_file_path.c_str());
  31. auto load_result = load_pair(cert_file_path.c_str(), key_file_path.c_str());
  32. REQUIRE((bool)load_result);
  33. REQUIRE(load_result.value().cert_data.bytes.size() == pair.value().cert_data.bytes.size());
  34. bool bytes_equal = load_result.value().cert_data.bytes == pair.value().cert_data.bytes;
  35. REQUIRE(bytes_equal);
  36. auto cn = get_common_name(value.cert.get());
  37. REQUIRE(cn);
  38. REQUIRE(cn.value() == "sample");
  39. }
  40. TEST_CASE("sha256 for certificate", "[support][tls]") {
  41. auto cert = read_file(locate_path("data/cert.der"));
  42. auto sha_result = sha256_digest(cert);
  43. REQUIRE((bool)sha_result);
  44. auto &sha = sha_result.value();
  45. REQUIRE(1 == 1);
  46. std::string expected = "b1b48b580b78b47c975a138b4aaa2988fc621795c95a2868e24d93b327e8858c";
  47. std::string got_str;
  48. for (std::size_t i = 0; i < sha.size(); i++) {
  49. got_str += fmt::format("{:02x}", (unsigned char)sha[i]);
  50. }
  51. REQUIRE(got_str == expected);
  52. auto enc = base32::encode(sha);
  53. REQUIRE(enc == "WG2IWWALPC2HZF22COFUVKRJRD6GEF4VZFNCQ2HCJWJ3GJ7IQWGA");
  54. }