1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "util/crypto/sha2.h"
6
7 #include <stddef.h>
8 #include <stdint.h>
9
10 #include "gmock/gmock.h"
11 #include "gtest/gtest.h"
12 #include "util/std_util.h"
13
14 namespace openscreen {
TEST(Sha256Test,Test1)15 TEST(Sha256Test, Test1) {
16 // Example B.1 from FIPS 180-2: one-block message.
17 std::string input = "abc";
18 constexpr uint8_t kExpected[] = {
19 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40,
20 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17,
21 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad};
22
23 uint8_t output[SHA256_DIGEST_LENGTH];
24 EXPECT_EQ(Error::None(), SHA256HashString(input, output));
25 EXPECT_THAT(output, testing::ElementsAreArray(kExpected));
26 }
27
TEST(Sha256Test,Test1_String)28 TEST(Sha256Test, Test1_String) {
29 // Same as the above, but using the wrapper that returns a std::string.
30 // Example B.1 from FIPS 180-2: one-block message.
31 std::string input = "abc";
32 constexpr uint8_t kExpected[] = {
33 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40,
34 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17,
35 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad};
36
37 const ErrorOr<std::string> output = SHA256HashString(input);
38 EXPECT_TRUE(output.is_value());
39 ASSERT_EQ(static_cast<size_t>(SHA256_DIGEST_LENGTH), output.value().size());
40 EXPECT_THAT(output.value(), testing::ElementsAreArray(kExpected));
41 }
42
TEST(Sha256Test,Test2)43 TEST(Sha256Test, Test2) {
44 // Example B.2 from FIPS 180-2: multi-block message.
45 std::string input =
46 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
47 constexpr uint8_t kExpected[] = {
48 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26,
49 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff,
50 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1};
51
52 uint8_t output[SHA256_DIGEST_LENGTH];
53 EXPECT_EQ(Error::None(), SHA256HashString(input, output));
54 EXPECT_THAT(output, testing::ElementsAreArray(kExpected));
55 }
56
TEST(Sha256Test,Test3)57 TEST(Sha256Test, Test3) {
58 // Example B.3 from FIPS 180-2: long message.
59 std::string input(1000000, 'a'); // 'a' repeated a million times
60 constexpr uint8_t kExpected[] = {
61 0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92, 0x81, 0xa1, 0xc7,
62 0xe2, 0x84, 0xd7, 0x3e, 0x67, 0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97,
63 0x20, 0x0e, 0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0};
64
65 uint8_t output[SHA256_DIGEST_LENGTH];
66 EXPECT_EQ(Error::None(), SHA256HashString(input, output));
67 EXPECT_THAT(output, testing::ElementsAreArray(kExpected));
68 }
69 } // namespace openscreen
70