2018-01-14 17:17:34 +11:00
|
|
|
/*
|
2018-08-04 15:18:16 +10:00
|
|
|
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
|
|
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
2018-01-14 17:17:34 +11:00
|
|
|
*
|
|
|
|
* Copyright 2015 Danny Robson <danny@nerdcruft.net>
|
|
|
|
*/
|
|
|
|
|
|
|
|
#ifndef CRUFT_CRYPTO_HASH_HMAC_HPP
|
|
|
|
#define CRUFT_CRYPTO_HASH_HMAC_HPP
|
|
|
|
|
2019-05-25 16:39:03 +10:00
|
|
|
#include <cruft/util/debug/assert.hpp>
|
2018-01-14 17:17:34 +11:00
|
|
|
#include <cruft/util/view.hpp>
|
|
|
|
|
|
|
|
#include <algorithm>
|
|
|
|
#include <utility>
|
|
|
|
|
|
|
|
|
|
|
|
namespace cruft::crypto::hash {
|
|
|
|
template <class HashT>
|
|
|
|
/// RFC 2104 key-hashing for message authentication
|
|
|
|
class HMAC {
|
|
|
|
public:
|
|
|
|
using digest_t = typename HashT::digest_t;
|
|
|
|
|
|
|
|
|
|
|
|
//---------------------------------------------------------------------
|
2018-08-05 14:51:17 +10:00
|
|
|
HMAC (cruft::view<const std::uint8_t*> key)
|
2018-01-14 17:17:34 +11:00
|
|
|
{
|
|
|
|
CHECK (!key.empty ());
|
|
|
|
|
|
|
|
static_assert (sizeof (m_ikey) == sizeof (m_okey), "key padding must match");
|
|
|
|
|
|
|
|
// If the key is larger than the blocklength, use the hash of the key
|
|
|
|
if (key.size () > HashT::BLOCK_SIZE) {
|
|
|
|
auto d = HashT{} (key);
|
|
|
|
auto tail = std::copy (d.begin (), d.end (), m_ikey.begin ());
|
|
|
|
std::fill (tail, std::end (m_ikey), 0);
|
|
|
|
// Use the key directly
|
|
|
|
} else {
|
|
|
|
auto tail = std::copy (key.begin (), key.end (), m_ikey.begin ());
|
|
|
|
std::fill (tail, m_ikey.end (), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
// copy and xor the key data to the okey
|
|
|
|
std::transform (
|
|
|
|
std::begin (m_ikey),
|
|
|
|
std::end (m_ikey),
|
|
|
|
std::begin (m_okey),
|
|
|
|
[] (auto v) { return v ^ OFILL; });
|
|
|
|
|
|
|
|
// just xor the ikey in place
|
|
|
|
std::transform (
|
|
|
|
m_ikey.begin (),
|
|
|
|
m_ikey.end (),
|
|
|
|
m_ikey.begin (),
|
|
|
|
[] (auto v) { return v ^ IFILL; });
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
//---------------------------------------------------------------------
|
|
|
|
template <typename ...DataT>
|
|
|
|
digest_t
|
|
|
|
operator() (DataT&&...data) const noexcept
|
|
|
|
{
|
|
|
|
HashT h;
|
|
|
|
return h (m_okey, h (m_ikey, std::forward<DataT> (data)...));
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
private:
|
|
|
|
//---------------------------------------------------------------------
|
|
|
|
static constexpr uint8_t IFILL = 0x36;
|
|
|
|
static constexpr uint8_t OFILL = 0x5C;
|
|
|
|
|
|
|
|
std::array<uint8_t,HashT::BLOCK_SIZE> m_ikey;
|
|
|
|
std::array<uint8_t,HashT::BLOCK_SIZE> m_okey;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
#endif
|