Data_deduplication_service
Service that will use hashes to deduplicate files
HashUtils.h
Go to the documentation of this file.
1 
2 
3 #ifndef DATA_DEDUPLICATION_SERVICE_HASHUTILS_H
4 #define DATA_DEDUPLICATION_SERVICE_HASHUTILS_H
5 
6 #include <array>
7 #include <string>
8 #include <sstream>
9 #include <iomanip>
10 
11 
12 #include <openssl/core.h>
13 #include <openssl/sha.h>
14 #include <openssl/md5.h>
15 #include <openssl/md4.h>
16 #include <openssl/md2.h>
17 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
19 namespace hash_utils {
20 
21  constexpr std::array<unsigned char *(*)(const unsigned char *d, size_t n, unsigned char *md), 6> funcs
22  = {&SHA224, &SHA256,
23  &MD5, &SHA384, &SHA512,&MD4};
24 
34  MD_4
35  };
36 
42  template<hash_function hash = MD_5>
43  std::string getHashStr(std::string_view stringView);
44 
48  static constexpr std::array<unsigned short, 6> hashFunctionSize
49  {
50  SHA224_DIGEST_LENGTH,
51  SHA256_DIGEST_LENGTH,
52  MD5_DIGEST_LENGTH,
53  SHA384_DIGEST_LENGTH,
54  SHA512_DIGEST_LENGTH,
55  MD4_DIGEST_LENGTH
56  };
57 
61  static constexpr std::array<const char *, 6> hashFunctionName
62  {
63  "sha224",
64  "sha256",
65  "md5",
66  "sha384",
67  "sha512",
68  "md4"
69  };
70 
71 
76  std::string stringToHex(std::string_view in);
77 
78  //todo remake for raw buffers
83  std::string hexToString(std::string_view in);
84 
85 
86  template<hash_function hash>
87  std::string getHashStr(std::string_view stringView) {
88  unsigned char md[hashFunctionSize[hash]];
89  funcs[hash](reinterpret_cast<const unsigned char *>(stringView.data()),
90  stringView.size(),
91  md
92  );
93 
94  std::stringstream ss;
95  for (size_t i = 0; i < hashFunctionSize[hash]; ++i) {
96  ss << std::hex << std::setw(2)
97  << std::setfill('0') << (int) md[i];
98  }
99  return ss.str();
100  }
101 
102 }
103 
104 #endif //DATA_DEDUPLICATION_SERVICE_HASHUTILS_H
hash utils namespace
Definition: HashUtils.h:19
hash_function
Definition: HashUtils.h:28
@ SHA_384
Definition: HashUtils.h:32
@ SHA_512
Definition: HashUtils.h:33
@ SHA_256
Definition: HashUtils.h:30
@ MD_4
Definition: HashUtils.h:34
@ MD_5
Definition: HashUtils.h:31
@ SHA_224
Definition: HashUtils.h:29
constexpr std::array< unsigned char *(*)(const unsigned char *d, size_t n, unsigned char *md), 6 > funcs
Definition: HashUtils.h:22
std::string getHashStr(std::string_view stringView)
Definition: HashUtils.h:87
std::string hexToString(std::string_view in)
Definition: HashUtils.cpp:15
std::string stringToHex(std::string_view in)
Definition: HashUtils.cpp:4