CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
hmac.h
Go to the documentation of this file.
1
6// //////////////////////////////////////////////////////////
7// hmac.h
8// Copyright (c) 2015 Stephan Brumme. All rights reserved.
9// see http://create.stephan-brumme.com/disclaimer.html
10//
11
12#pragma once
13
14// based on http://tools.ietf.org/html/rfc2104
15// see also http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
16
34
35#include <string>
36#include <cstring> // memcpy
37
38 // Added namespace to avoid clash with OpenSSL
39namespace hash {
40
42template <typename HashMethod>
43std::string hmac(const void* data, size_t numDataBytes, const void* key, size_t numKeyBytes)
44{
45 // initialize key with zeros
46 unsigned char usedKey[HashMethod::BlockSize] = {0};
47
48 // adjust length of key: must contain exactly blockSize bytes
49 if (numKeyBytes <= HashMethod::BlockSize)
50 {
51 // copy key
52 memcpy(usedKey, key, numKeyBytes);
53 }
54 else
55 {
56 // shorten key: usedKey = hashed(key)
57 HashMethod keyHasher;
58 keyHasher.add(key, numKeyBytes);
59 keyHasher.getHash(usedKey);
60 }
61
62 // create initial XOR padding
63 for (size_t i = 0; i < HashMethod::BlockSize; i++)
64 usedKey[i] ^= 0x36;
65
66 // inside = hash((usedKey ^ 0x36) + data)
67 unsigned char inside[HashMethod::HashBytes];
68 HashMethod insideHasher;
69 insideHasher.add(usedKey, HashMethod::BlockSize);
70 insideHasher.add(data, numDataBytes);
71 insideHasher.getHash(inside);
72
73 // undo usedKey's previous 0x36 XORing and apply a XOR by 0x5C
74 for (size_t i = 0; i < HashMethod::BlockSize; i++)
75 usedKey[i] ^= 0x5C ^ 0x36;
76
77 // hash((usedKey ^ 0x5C) + hash((usedKey ^ 0x36) + data))
78 HashMethod finalHasher;
79 finalHasher.add(usedKey, HashMethod::BlockSize);
80 finalHasher.add(inside, HashMethod::HashBytes);
81
82 return finalHasher.getHash();
83}
84
85
87template <typename HashMethod>
88std::string hmac(const std::string& data, const std::string& key)
89{
90 return hmac<HashMethod>(data.c_str(), data.size(), key.c_str(), key.size());
91}
92
93} // namespace hash
Usage: std::string msg = "The quick brown fox jumps over the lazy dog"; std::string key = "key"; std:...
Definition crc32.h:28
std::string hmac(const void *data, size_t numDataBytes, const void *key, size_t numKeyBytes)
compute HMAC hash of data and key using MD5, SHA1 or SHA256
Definition hmac.h:43