|
13 | 13 | * |
14 | 14 | */ |
15 | 15 |
|
16 | | - |
17 | 16 | #ifndef SRC_UTILS_SHA1_H_ |
18 | 17 | #define SRC_UTILS_SHA1_H_ |
19 | 18 |
|
20 | | -#include <algorithm> |
21 | | -#include <iostream> |
22 | 19 | #include <string> |
| 20 | +#include <cassert> |
| 21 | + |
| 22 | +#include "src/utils/string.h" |
| 23 | +#include "mbedtls/sha1.h" |
| 24 | + |
| 25 | +namespace modsecurity::Utils { |
| 26 | + |
23 | 27 |
|
24 | | -namespace modsecurity { |
25 | | -namespace Utils { |
| 28 | +using DigestOp = int (*)(const unsigned char *, size_t, unsigned char []); |
26 | 29 |
|
27 | | -class Sha1 { |
| 30 | + |
| 31 | +template<DigestOp digestOp, int DigestSize> |
| 32 | +class DigestImpl { |
28 | 33 | public: |
29 | | - Sha1() { } |
30 | 34 |
|
31 | | - static std::string hexdigest(const std::string& input); |
32 | | - static std::string digest(const std::string& input); |
| 35 | + static std::string digest(const std::string& input) { |
| 36 | + return digestHelper(input, [](const auto digest) { |
| 37 | + return std::string(digest); |
| 38 | + }); |
| 39 | + } |
| 40 | + |
| 41 | + static void digestReplace(std::string& value) { |
| 42 | + digestHelper(value, [&value](const auto digest) mutable { |
| 43 | + value = digest; |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + static std::string hexdigest(const std::string &input) { |
| 48 | + return digestHelper(input, [](const auto digest) { |
| 49 | + return utils::string::string_to_hex(digest); |
| 50 | + }); |
| 51 | + } |
| 52 | + |
| 53 | +private: |
| 54 | + |
| 55 | + template<typename ConvertOp> |
| 56 | + static auto digestHelper(const std::string &input, |
| 57 | + ConvertOp convertOp) -> auto { |
| 58 | + char digest[DigestSize]; |
| 59 | + |
| 60 | + auto ret = digestOp(reinterpret_cast<const unsigned char *>(input.c_str()), |
| 61 | + input.size(), reinterpret_cast<unsigned char *>(digest)); |
| 62 | + assert(ret == 0); |
| 63 | + |
| 64 | + return convertOp(std::string_view(digest, DigestSize)); |
| 65 | + } |
33 | 66 | }; |
34 | 67 |
|
35 | | -} // namespace Utils |
36 | | -} // namespace modsecurity |
| 68 | + |
| 69 | +class Sha1 : public DigestImpl<&mbedtls_sha1, 20> { |
| 70 | +}; |
| 71 | + |
| 72 | + |
| 73 | +} // namespace modsecurity::Utils |
37 | 74 |
|
38 | 75 | #endif // SRC_UTILS_SHA1_H_ |
0 commit comments