From e7ba83cdcc5bb7beff4ebb572e06086b9da43d83 Mon Sep 17 00:00:00 2001 From: Aster Seker Date: Thu, 4 Sep 2025 02:23:55 +0300 Subject: [PATCH] fix(utils): use wider diff type for constant_time_equals Initialize diff with boolean size comparison to avoid truncation when lengths differ by multiples of 256. Add tests covering 256- and 512-byte length mismatches. --- hmac_utils.cpp | 2 +- test_all.cpp | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/hmac_utils.cpp b/hmac_utils.cpp index c83cc39..3792e6c 100644 --- a/hmac_utils.cpp +++ b/hmac_utils.cpp @@ -7,7 +7,7 @@ namespace hmac { bool constant_time_equals(const std::string &a, const std::string &b) { size_t max_len = a.size() > b.size() ? a.size() : b.size(); - unsigned char diff = static_cast(a.size() ^ b.size()); + unsigned int diff = (a.size() != b.size()); for (size_t i = 0; i < max_len; ++i) { unsigned char ac = i < a.size() ? static_cast(a[i]) : 0; unsigned char bc = i < b.size() ? static_cast(b[i]) : 0; diff --git a/test_all.cpp b/test_all.cpp index d070c29..4c4e8d6 100644 --- a/test_all.cpp +++ b/test_all.cpp @@ -58,6 +58,14 @@ TEST(UtilsTest, ConstantTimeEqualsMismatch) { EXPECT_FALSE(hmac::constant_time_equals("alpha", "alphabet")); } +TEST(UtilsTest, ConstantTimeEqualsLengthMultiples256) { + std::string base(256, 'a'); + std::string plus256 = base + std::string(256, '\0'); + std::string plus512 = base + std::string(512, '\0'); + EXPECT_FALSE(hmac::constant_time_equals(base, plus256)); + EXPECT_FALSE(hmac::constant_time_equals(base, plus512)); +} + TEST(HMACTest, SHA256) { const std::string key = "12345"; const std::string input = "grape";