Skip to content

Commit e7ba83c

Browse files
committed
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.
1 parent d416ceb commit e7ba83c

2 files changed

Lines changed: 9 additions & 1 deletion

File tree

hmac_utils.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace hmac {
77

88
bool constant_time_equals(const std::string &a, const std::string &b) {
99
size_t max_len = a.size() > b.size() ? a.size() : b.size();
10-
unsigned char diff = static_cast<unsigned char>(a.size() ^ b.size());
10+
unsigned int diff = (a.size() != b.size());
1111
for (size_t i = 0; i < max_len; ++i) {
1212
unsigned char ac = i < a.size() ? static_cast<unsigned char>(a[i]) : 0;
1313
unsigned char bc = i < b.size() ? static_cast<unsigned char>(b[i]) : 0;

test_all.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,14 @@ TEST(UtilsTest, ConstantTimeEqualsMismatch) {
5858
EXPECT_FALSE(hmac::constant_time_equals("alpha", "alphabet"));
5959
}
6060

61+
TEST(UtilsTest, ConstantTimeEqualsLengthMultiples256) {
62+
std::string base(256, 'a');
63+
std::string plus256 = base + std::string(256, '\0');
64+
std::string plus512 = base + std::string(512, '\0');
65+
EXPECT_FALSE(hmac::constant_time_equals(base, plus256));
66+
EXPECT_FALSE(hmac::constant_time_equals(base, plus512));
67+
}
68+
6169
TEST(HMACTest, SHA256) {
6270
const std::string key = "12345";
6371
const std::string input = "grape";

0 commit comments

Comments
 (0)