/* * 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/. * * Copyright 2015 Danny Robson */ #ifndef CRUFT_CRYPTO_HASH_HMAC_HPP #define CRUFT_CRYPTO_HASH_HMAC_HPP #include #include #include #include namespace cruft::crypto::hash { template /// RFC 2104 key-hashing for message authentication class HMAC { public: using digest_t = typename HashT::digest_t; //--------------------------------------------------------------------- HMAC (cruft::view key) { 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 digest_t operator() (DataT&&...data) const noexcept { HashT h; return h (m_okey, h (m_ikey, std::forward (data)...)); }; private: //--------------------------------------------------------------------- static constexpr uint8_t IFILL = 0x36; static constexpr uint8_t OFILL = 0x5C; std::array m_ikey; std::array m_okey; }; } #endif