Kinetic C/C++ Client
 All Classes Functions Variables Pages
hmac_provider.cc
1 /*
2  * kinetic-cpp-client
3  * Copyright (C) 2014 Seagate Technology.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  */
20 
21 #include "kinetic/hmac_provider.h"
22 
23 #include <list>
24 #include <arpa/inet.h>
25 
26 #include <openssl/hmac.h>
27 #include <openssl/sha.h>
28 #include "glog/logging.h"
29 
30 namespace kinetic {
31 
32 using com::seagate::kinetic::client::proto::Message;
33 
34 HmacProvider::HmacProvider() {}
35 
36 std::string HmacProvider::ComputeHmac(const Message& message,
37  const std::string& key) const {
38  HMAC_CTX *ctx = HMAC_CTX_new();
39  HMAC_Init_ex(ctx, key.c_str(), key.length(), EVP_sha1(), NULL);
40 
41  if (message.commandbytes().length() != 0) {
42  uint32_t message_length_bigendian = htonl(message.commandbytes().length());
43  HMAC_Update(ctx, reinterpret_cast<unsigned char *>(&message_length_bigendian),
44  sizeof(uint32_t));
45  HMAC_Update(ctx, reinterpret_cast<const unsigned char *>(message.commandbytes().c_str()),
46  message.commandbytes().length());
47  }
48 
49  unsigned char result[SHA_DIGEST_LENGTH];
50  unsigned int result_length = SHA_DIGEST_LENGTH;
51  HMAC_Final(ctx, result, &result_length);
52  HMAC_CTX_free(ctx);
53 
54  return std::string(reinterpret_cast<char *>(result), result_length);
55 }
56 
57 bool HmacProvider::ValidateHmac(const Message& message, const std::string& key) const {
58  std::string correct_hmac(ComputeHmac(message, key));
59 
60  if (!message.has_hmacauth()) {
61  return false;
62  }
63 
64  const std::string &provided_hmac = message.hmacauth().hmac();
65 
66  if (provided_hmac.length() != correct_hmac.length()) {
67  return false;
68  }
69 
70  int result = 0;
71  for (size_t i = 0; i < correct_hmac.length(); i++) {
72  result |= provided_hmac[i] ^ correct_hmac[i];
73  }
74 
75  return result == 0;
76 }
77 
78 } // namespace kinetic