diff --git a/lib/base/tlsutility.cpp b/lib/base/tlsutility.cpp index ac29fbc26..264a0872f 100644 --- a/lib/base/tlsutility.cpp +++ b/lib/base/tlsutility.cpp @@ -762,9 +762,13 @@ String SHA1(const String& s, bool binary) if (binary) return String(reinterpret_cast(digest), reinterpret_cast(digest + SHA_DIGEST_LENGTH)); + static const char hexdigits[] = "0123456789abcdef"; char output[SHA_DIGEST_LENGTH*2+1]; - for (int i = 0; i < 20; i++) - sprintf(output + 2 * i, "%02x", digest[i]); + for (int i = 0; i < SHA_DIGEST_LENGTH; i++) { + output[2*i] = hexdigits[digest[i] >> 4]; + output[2*i + 1] = hexdigits[digest[i] & 0xf]; + } + output[2*SHA_DIGEST_LENGTH] = 0; return output; } diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 3bcf04319..cb691f56c 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -20,6 +20,7 @@ set(base_test_SOURCES base-stream.cpp base-string.cpp base-timer.cpp + base-tlsutility.cpp base-type.cpp base-utility.cpp base-value.cpp @@ -105,6 +106,7 @@ add_boost_test(base base_timer/interval base_timer/invoke base_timer/scope + base_tlsutility/sha1 base_type/gettype base_type/assign base_type/byname diff --git a/test/base-tlsutility.cpp b/test/base-tlsutility.cpp new file mode 100644 index 000000000..c66cef474 --- /dev/null +++ b/test/base-tlsutility.cpp @@ -0,0 +1,38 @@ +/* Icinga 2 | (c) 2021 Icinga GmbH | GPLv2+ */ + +#include "base/tlsutility.hpp" +#include +#include +#include + +using namespace icinga; + +BOOST_AUTO_TEST_SUITE(base_tlsutility) + +BOOST_AUTO_TEST_CASE(sha1) +{ + std::string allchars; + for (size_t i = 0; i < 256; i++) { + allchars.push_back(i); + } + + std::vector> testdata = { + {"", "da39a3ee5e6b4b0d3255bfef95601890afd80709"}, + {"icinga", "f172c5e9e4d840a55356882a2b644846b302b216"}, + {"Icinga", "b3bdae77f60d9065f6152c7e3bbd351fa65e6fab"}, + {"ICINGA", "335da1d814abeef09b4623e2ce5169140c267a39"}, + {"#rX|wlcM:.8)uVmxz", "99dc4d34caf36c6d6b08404135f1a7286211be1e"}, + {"AgbM;Z8Tz1!Im,kecZWs", "aa793bef1ca307012980ae5ae046b7e929f6ed99"}, + {"yLUA4vKQ~24W}ahI;i?NLLS", "5e1a5ee3bd9fae5150681ef656ad43d9cb8e7005"}, + {allchars, "4916d6bdb7f78e6803698cab32d1586ea457dfc8"}, + }; + + for (const auto& p : testdata) { + const auto& input = p.first; + const auto& expected = p.second; + auto output = SHA1(input); + BOOST_CHECK_MESSAGE(output == expected, "SHA1('" << input << "') should be " << expected << ", got " << output); + } +} + +BOOST_AUTO_TEST_SUITE_END()