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 "gtest/gtest.h"
17
18using namespace llvm;
19
20namespace {
21
22static std::string toHex(ArrayRef<uint8_t> Input) {
23 static const char *const LUT = "0123456789abcdef";
24 size_t Length = Input.size();
25
26 std::string Output;
27 Output.reserve(res: 2 * Length);
28 for (size_t i = 0; i < Length; ++i) {
29 const unsigned char c = Input[i];
30 Output.push_back(c: LUT[c >> 4]);
31 Output.push_back(c: LUT[c & 15]);
32 }
33 return Output;
34}
35
36/// Tests an arbitrary set of bytes passed as \p Input.
37void TestSHA256Sum(ArrayRef<uint8_t> Input, StringRef Final) {
38 SHA256 Hash;
39 Hash.update(Data: Input);
40 auto hash = Hash.final();
41 auto hashStr = toHex(Input: hash);
42 EXPECT_EQ(hashStr, Final);
43}
44
45using KV = std::pair<const char *, const char *>;
46
47TEST(SHA256Test, SHA256) {
48 std::array<KV, 5> testvectors{
49 KV{"",
50 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"},
51 KV{"a",
52 "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb"},
53 KV{"abc",
54 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"},
55 KV{"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
56 "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"},
57 KV{"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklm"
58 "nopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
59 "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1"}};
60
61 for (auto input_expected : testvectors) {
62 auto str = std::get<0>(in&: input_expected);
63 auto expected = std::get<1>(in&: input_expected);
64 TestSHA256Sum(Input: {reinterpret_cast<const uint8_t *>(str), strlen(s: str)},
65 Final: expected);
66 }
67
68 std::string rep(1000, 'a');
69 SHA256 Hash;
70 for (int i = 0; i < 1000; ++i) {
71 Hash.update(Data: {reinterpret_cast<const uint8_t *>(rep.data()), rep.size()});
72 }
73 auto hash = Hash.final();
74 auto hashStr = toHex(Input: hash);
75 EXPECT_EQ(hashStr,
76 "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
77}
78
79} // namespace
80

source code of llvm/unittests/Support/SHA256.cpp