011-tls-util.cpp 2.4 KB

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