129cf406bef149a65a047a09d182fa0a464588f9
[folly.git] / folly / ssl / test / OpenSSLHashTest.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <folly/ssl/OpenSSLHash.h>
18
19 #include <gtest/gtest.h>
20
21 #include <folly/io/IOBufQueue.h>
22
23 using namespace std;
24 using namespace folly;
25 using namespace folly::ssl;
26
27 namespace {
28
29 class OpenSSLHashTest : public testing::Test {};
30
31 }
32
33 TEST_F(OpenSSLHashTest, sha256) {
34   IOBuf buf;
35   buf.prependChain(IOBuf::wrapBuffer(ByteRange(StringPiece("foo"))));
36   buf.prependChain(IOBuf::wrapBuffer(ByteRange(StringPiece("bar"))));
37   EXPECT_EQ(3, buf.countChainElements());
38   EXPECT_EQ(6, buf.computeChainDataLength());
39
40   auto expected = vector<uint8_t>(32);
41   auto combined = ByteRange(StringPiece("foobar"));
42   SHA256(combined.data(), combined.size(), expected.data());
43
44   auto out = vector<uint8_t>(32);
45   OpenSSLHash::sha256(range(out), buf);
46   EXPECT_EQ(expected, out);
47 }
48
49 TEST_F(OpenSSLHashTest, hmac_sha256) {
50   auto key = ByteRange(StringPiece("qwerty"));
51
52   IOBuf buf;
53   buf.prependChain(IOBuf::wrapBuffer(ByteRange(StringPiece("foo"))));
54   buf.prependChain(IOBuf::wrapBuffer(ByteRange(StringPiece("bar"))));
55   EXPECT_EQ(3, buf.countChainElements());
56   EXPECT_EQ(6, buf.computeChainDataLength());
57
58   auto expected = vector<uint8_t>(32);
59   auto combined = ByteRange(StringPiece("foobar"));
60   HMAC(
61       EVP_sha256(),
62       key.data(), key.size(),
63       combined.data(), combined.size(),
64       expected.data(), nullptr);
65
66   auto out = vector<uint8_t>(32);
67   OpenSSLHash::hmac_sha256(range(out), key, buf);
68   EXPECT_EQ(expected, out);
69 }