2 * Copyright 2016-present Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #include <folly/ssl/OpenSSLHash.h>
19 #include <folly/io/IOBufQueue.h>
20 #include <folly/portability/GTest.h>
23 using namespace folly;
24 using namespace folly::ssl;
28 class OpenSSLHashTest : public testing::Test {};
31 TEST_F(OpenSSLHashTest, sha256) {
33 buf.prependChain(IOBuf::wrapBuffer(ByteRange(StringPiece("foo"))));
34 buf.prependChain(IOBuf::wrapBuffer(ByteRange(StringPiece("bar"))));
35 EXPECT_EQ(3, buf.countChainElements());
36 EXPECT_EQ(6, buf.computeChainDataLength());
38 auto expected = vector<uint8_t>(32);
39 auto combined = ByteRange(StringPiece("foobar"));
40 SHA256(combined.data(), combined.size(), expected.data());
42 auto out = vector<uint8_t>(32);
43 OpenSSLHash::sha256(range(out), buf);
44 EXPECT_EQ(expected, out);
47 TEST_F(OpenSSLHashTest, sha256_hashcopy) {
48 std::array<uint8_t, 32> expected, actual;
50 OpenSSLHash::Digest digest;
51 digest.hash_init(EVP_sha256());
52 digest.hash_update(ByteRange(StringPiece("foobar")));
54 OpenSSLHash::Digest copy(digest);
56 digest.hash_final(range(expected));
57 copy.hash_final(range(actual));
59 EXPECT_EQ(expected, actual);
62 TEST_F(OpenSSLHashTest, sha256_hashcopy_intermediate) {
63 std::array<uint8_t, 32> expected, actual;
65 OpenSSLHash::Digest digest;
66 digest.hash_init(EVP_sha256());
67 digest.hash_update(ByteRange(StringPiece("foo")));
69 OpenSSLHash::Digest copy(digest);
71 digest.hash_update(ByteRange(StringPiece("bar")));
72 copy.hash_update(ByteRange(StringPiece("bar")));
74 digest.hash_final(range(expected));
75 copy.hash_final(range(actual));
77 EXPECT_EQ(expected, actual);
80 TEST_F(OpenSSLHashTest, hmac_sha256) {
81 auto key = ByteRange(StringPiece("qwerty"));
84 buf.prependChain(IOBuf::wrapBuffer(ByteRange(StringPiece("foo"))));
85 buf.prependChain(IOBuf::wrapBuffer(ByteRange(StringPiece("bar"))));
86 EXPECT_EQ(3, buf.countChainElements());
87 EXPECT_EQ(6, buf.computeChainDataLength());
89 auto expected = vector<uint8_t>(32);
90 auto combined = ByteRange(StringPiece("foobar"));
100 auto out = vector<uint8_t>(32);
101 OpenSSLHash::hmac_sha256(range(out), key, buf);
102 EXPECT_EQ(expected, out);