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;
39  HMAC_CTX_init(&ctx);
40  HMAC_Init_ex(&ctx, key.c_str(), key.length(), EVP_sha1(), NULL);
41 
42  if (message.commandbytes().length() != 0) {
43  uint32_t message_length_bigendian = htonl(message.commandbytes().length());
44  HMAC_Update(&ctx, reinterpret_cast<unsigned char *>(&message_length_bigendian),
45  sizeof(uint32_t));
46  HMAC_Update(&ctx, reinterpret_cast<const unsigned char *>(message.commandbytes().c_str()),
47  message.commandbytes().length());
48  }
49 
50  unsigned char result[SHA_DIGEST_LENGTH];
51  unsigned int result_length = SHA_DIGEST_LENGTH;
52  HMAC_Final(&ctx, result, &result_length);
53  HMAC_CTX_cleanup(&ctx);
54 
55  return std::string(reinterpret_cast<char *>(result), result_length);
56 }
57 
58 bool HmacProvider::ValidateHmac(const Message& message, const std::string& key) const {
59  std::string correct_hmac(ComputeHmac(message, key));
60 
61  if (!message.has_hmacauth()) {
62  return false;
63  }
64 
65  const std::string &provided_hmac = message.hmacauth().hmac();
66 
67  if (provided_hmac.length() != correct_hmac.length()) {
68  return false;
69  }
70 
71  int result = 0;
72  for (size_t i = 0; i < correct_hmac.length(); i++) {
73  result |= provided_hmac[i] ^ correct_hmac[i];
74  }
75 
76  return result == 0;
77 }
78 
79 } // namespace kinetic