1 //===- llvm/unittest/Support/SHA256Test.cpp - SHA256 tests 2 //----------------------===// 3 // 4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 5 // See https://llvm.org/LICENSE.txt for license information. 6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements unit tests for the SHA256 functions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Support/SHA256.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "gtest/gtest.h" 18 19 using namespace llvm; 20 21 namespace { 22 23 static std::string toHex(StringRef Input) { 24 static const char *const LUT = "0123456789abcdef"; 25 size_t Length = Input.size(); 26 27 std::string Output; 28 Output.reserve(2 * Length); 29 for (size_t i = 0; i < Length; ++i) { 30 const unsigned char c = Input[i]; 31 Output.push_back(LUT[c >> 4]); 32 Output.push_back(LUT[c & 15]); 33 } 34 return Output; 35 } 36 37 /// Tests an arbitrary set of bytes passed as \p Input. 38 void TestSHA256Sum(ArrayRef<uint8_t> Input, StringRef Final) { 39 SHA256 Hash; 40 Hash.update(Input); 41 auto hash = Hash.final(); 42 auto hashStr = toHex(hash); 43 EXPECT_EQ(hashStr, Final); 44 } 45 46 using KV = std::pair<const char *, const char *>; 47 48 TEST(SHA256Test, SHA256) { 49 std::array<KV, 5> testvectors{ 50 KV{"", 51 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, 52 KV{"a", 53 "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"}, 54 KV{"abc", 55 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}, 56 KV{"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 57 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"}, 58 KV{"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklm" 59 "nopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", 60 "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"}}; 61 62 for (auto input_expected : testvectors) { 63 auto str = std::get<0>(input_expected); 64 auto expected = std::get<1>(input_expected); 65 TestSHA256Sum({reinterpret_cast<const uint8_t *>(str), strlen(str)}, 66 expected); 67 } 68 69 std::string rep(1000, 'a'); 70 SHA256 Hash; 71 for (int i = 0; i < 1000; ++i) { 72 Hash.update({reinterpret_cast<const uint8_t *>(rep.data()), rep.size()}); 73 } 74 auto hash = Hash.final(); 75 auto hashStr = toHex(hash); 76 EXPECT_EQ(hashStr, 77 "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); 78 } 79 80 } // namespace 81