diff --git a/hmac.cpp b/hmac.cpp index ad09b55..e997937 100644 --- a/hmac.cpp +++ b/hmac.cpp @@ -1,5 +1,6 @@ #include #include +#include #include "hmac.hpp" namespace hmac { @@ -123,6 +124,8 @@ namespace hmac { } // Step 3: Compute inner hash + if (msg_len > SIZE_MAX - block_size) + throw std::overflow_error("msg_len + block_size overflow"); std::vector inner_data; inner_data.reserve(block_size + msg_len); inner_data.insert(inner_data.end(), ikeypad.begin(), ikeypad.end()); @@ -130,6 +133,8 @@ namespace hmac { std::vector inner_hash = get_hash(inner_data.data(), inner_data.size(), type); // Step 4: Compute final HMAC + if (digest_size > SIZE_MAX - block_size) + throw std::overflow_error("digest_size + block_size overflow"); std::vector outer_data; outer_data.reserve(block_size + digest_size); outer_data.insert(outer_data.end(), okeypad.begin(), okeypad.end()); diff --git a/test_all.cpp b/test_all.cpp index d2c9474..656f42c 100644 --- a/test_all.cpp +++ b/test_all.cpp @@ -107,6 +107,15 @@ TEST(HMACTest, InvalidTypeThrows) { EXPECT_THROW(hmac::get_hmac(key, 3, msg, 3, invalid), std::invalid_argument); } +TEST(HMACTest, MsgLenOverflowThrows) { + const char key[] = "key"; + const char msg[] = "a"; + size_t huge_len = std::numeric_limits::max() - + hmac_hash::SHA256::SHA224_256_BLOCK_SIZE + 1; + EXPECT_THROW(hmac::get_hmac(key, sizeof(key) - 1, msg, huge_len, + hmac::TypeHash::SHA256), std::overflow_error); +} + TEST(HMACTest, InvalidTypeThrowsString) { const std::string key = "key"; const std::string msg = "abc";