llvm.org GIT mirror llvm / 6356463
Add convenient functions to compute hashes of byte vectors. In many sitautions, you just want to compute a hash for one chunk of data. This patch adds convenient functions for that purpose. Differential Revision: https://reviews.llvm.org/D26988 git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@287726 91177308-0d34-0410-b5e6-96231b3b80d8 Rui Ueyama 3 years ago
6 changed file(s) with 46 addition(s) and 1 deletion(s). Raw diff Collapse all Expand all
3030 #include "llvm/ADT/SmallString.h"
3131 #include "llvm/Support/DataTypes.h"
3232 #include "llvm/Support/Endian.h"
33 #include
3334
3435 namespace llvm {
3536 template class ArrayRef;
6162 /// deposited into \p Str. The result will be of length 32.
6263 static void stringifyResult(MD5Result &Result, SmallString<32> &Str);
6364
65 /// \brief Computes the hash for a given bytes.
66 static std::array hash(ArrayRef Data);
67
6468 private:
6569 const uint8_t *body(ArrayRef Data);
6670 };
1717
1818 #include "llvm/ADT/ArrayRef.h"
1919
20 #include
2021 #include
2122
2223 namespace llvm {
5253 /// made into update.
5354 StringRef result();
5455
56 /// Returns a raw 160-bit SHA1 hash for the given data.
57 static std::array hash(ArrayRef Data);
58
5559 private:
5660 /// Define some constants.
5761 /// "static constexpr" would be cleaner but MSVC does not support it yet.
282282 Res << format("%.2x", Result[i]);
283283 }
284284
285 }
285 std::array MD5::hash(ArrayRef Data) {
286 MD5 Hash;
287 Hash.update(Data);
288 MD5::MD5Result Res;
289 Hash.final(Res);
290
291 std::array Arr;
292 memcpy(Arr.data(), Res, sizeof(Res));
293 return Arr;
294 }
295 }
268268 // Return pointer to hash (20 characters)
269269 return Hash;
270270 }
271
272 std::array SHA1::hash(ArrayRef Data) {
273 SHA1 Hash;
274 Hash.update(Data);
275 StringRef S = Hash.final().data();
276
277 std::array Arr;
278 memcpy(Arr.data(), S.data(), S.size());
279 return Arr;
280 }
5656 "81948d1f1554f58cd1a56ebb01f808cb");
5757 TestMD5Sum("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b");
5858 }
59
60 TEST(MD5HashTest, MD5) {
61 ArrayRef Input((const uint8_t *)"abcdefghijklmnopqrstuvwxyz", 26);
62 std::array Vec = MD5::hash(Input);
63 MD5::MD5Result MD5Res;
64 SmallString<32> Res;
65 memcpy(MD5Res, Vec.data(), Vec.size());
66 MD5::stringifyResult(MD5Res, Res);
67 EXPECT_EQ(Res, "c3fcd3d76192e4007dfb496cca67e13b");
5968 }
69 }
3636 ASSERT_EQ("2EF7BDE608CE5404E97D5F042F95F89F1C232871", Hash);
3737 }
3838
39 TEST(sha1_hash_test, Basic) {
40 ArrayRef Input((const uint8_t *)"Hello World!", 12);
41 std::array Vec = SHA1::hash(Input);
42 std::string Hash = toHex({(const char *)Vec.data(), 20});
43 ASSERT_EQ("2EF7BDE608CE5404E97D5F042F95F89F1C232871", Hash);
44 }
45
3946 // Check that getting the intermediate hash in the middle of the stream does
4047 // not invalidate the final result.
4148 TEST(raw_sha1_ostreamTest, Intermediate) {