From 884358995046d67b69b9ddc7f9fcc934a7609c74 Mon Sep 17 00:00:00 2001 From: hashlag <90853356+hashlag@users.noreply.github.com> Date: Tue, 26 Aug 2025 00:37:13 +0300 Subject: [PATCH] Make Hmac rekey-initializable (like Arc4Gen) --- Chaos/Mac/Hmac.hpp | 39 +++++++++++++++++++++++++++++++++--- ChaosTests/Mac/HmacTests.cpp | 13 ++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/Chaos/Mac/Hmac.hpp b/Chaos/Mac/Hmac.hpp index 2b983c3..aafbfaf 100644 --- a/Chaos/Mac/Hmac.hpp +++ b/Chaos/Mac/Hmac.hpp @@ -6,6 +6,7 @@ #include #include "Hash/Hasher.hpp" +#include "Service/ChaosException.hpp" namespace Chaos::Mac::Hmac { @@ -15,23 +16,33 @@ template Hmac(InputIt keyBegin, InputIt keyEnd) { - Key_ = GenerateKey(keyBegin, keyEnd); + RekeyImpl(keyBegin, keyEnd); + } - KeyType ipaddedKey = PadKey(Key_); - Hasher_.Update(ipaddedKey.begin(), ipaddedKey.end()); + template + void Rekey(InputIt keyBegin, InputIt keyEnd) + { + RekeyImpl(keyBegin, keyEnd); } template void Update(InputIt begin, InputIt end) { + EnsureInitialized(); Hasher_.Update(begin, end); } typename HasherImpl::HashType Finish() { + EnsureInitialized(); + auto innerDigest = Hasher_.Finish().GetRawDigest(); Hasher_.Reset(); @@ -49,9 +60,19 @@ private: static constexpr uint8_t OPAD_BYTE = 0x5c; static constexpr uint8_t IPAD_BYTE = 0x36; + bool IsInitialized_; + KeyType Key_; HasherImpl Hasher_; + void EnsureInitialized() const + { + if (!IsInitialized_) + { + throw Service::ChaosException("Hmac: not initialized"); + } + } + template static KeyType GenerateKey(InputIt keyBegin, InputIt keyEnd) { @@ -108,6 +129,18 @@ private: return paddedKey; } + + template + void RekeyImpl(InputIt keyBegin, InputIt keyEnd) + { + Key_ = GenerateKey(keyBegin, keyEnd); + Hasher_.Reset(); + + KeyType ipaddedKey = PadKey(Key_); + Hasher_.Update(ipaddedKey.begin(), ipaddedKey.end()); + + IsInitialized_ = true; + } }; } // namespace Chaos::Mac::Hmac diff --git a/ChaosTests/Mac/HmacTests.cpp b/ChaosTests/Mac/HmacTests.cpp index f334714..57c7239 100644 --- a/ChaosTests/Mac/HmacTests.cpp +++ b/ChaosTests/Mac/HmacTests.cpp @@ -72,3 +72,16 @@ TEST(HmacTests, LongKeyTest) ASSERT_EQ("99459b85e800f3e5eab24e1c945794f8", hmacMd5(key, data)); } } + +TEST(HmacTests, UninitializedHmacTest) +{ + std::array in; + in.fill(0); + + { + Hmac hmac; + + ASSERT_THROW(hmac.Update(in.begin(), in.end()), Chaos::Service::ChaosException); + ASSERT_THROW(hmac.Finish(), Chaos::Service::ChaosException); + } +}