utils: Add a constant time chunk_equals() variant for cryptographic purposes
This commit is contained in:
@@ -60,6 +60,32 @@ START_TEST(test_chunk_equals)
|
||||
}
|
||||
END_TEST
|
||||
|
||||
/*******************************************************************************
|
||||
* equals_const
|
||||
*/
|
||||
|
||||
START_TEST(test_chunk_equals_const)
|
||||
{
|
||||
chunk_t chunk = chunk_from_str("chunk");
|
||||
chunk_t chunk_a, chunk_b;
|
||||
|
||||
chunk_a = chunk_empty;
|
||||
chunk_b = chunk_empty;
|
||||
ck_assert(!chunk_equals_const(chunk_a, chunk_b));
|
||||
|
||||
chunk_a = chunk;
|
||||
ck_assert(!chunk_equals_const(chunk_a, chunk_b));
|
||||
chunk_b = chunk;
|
||||
ck_assert(chunk_equals_const(chunk_a, chunk_b));
|
||||
|
||||
chunk_b = chunk_from_str("asdf");
|
||||
ck_assert(!chunk_equals_const(chunk_a, chunk_b));
|
||||
|
||||
chunk_b = chunk_from_str("chunk");
|
||||
ck_assert(chunk_equals_const(chunk_a, chunk_b));
|
||||
}
|
||||
END_TEST
|
||||
|
||||
/*******************************************************************************
|
||||
* chunk_compare test
|
||||
*/
|
||||
@@ -1013,6 +1039,7 @@ Suite *chunk_suite_create()
|
||||
|
||||
tc = tcase_create("equals");
|
||||
tcase_add_test(tc, test_chunk_equals);
|
||||
tcase_add_test(tc, test_chunk_equals_const);
|
||||
suite_add_tcase(s, tc);
|
||||
|
||||
tc = tcase_create("chunk_compare");
|
||||
|
||||
@@ -309,6 +309,19 @@ static inline bool chunk_equals(chunk_t a, chunk_t b)
|
||||
a.len == b.len && memeq(a.ptr, b.ptr, a.len);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two chunks for equality, constant time for cryptographic purposes.
|
||||
*
|
||||
* Note that this function is constant time only for chunks with the same
|
||||
* length, i.e. it does not protect against guessing the length of one of the
|
||||
* chunks.
|
||||
*/
|
||||
static inline bool chunk_equals_const(chunk_t a, chunk_t b)
|
||||
{
|
||||
return a.ptr != NULL && b.ptr != NULL &&
|
||||
a.len == b.len && memeq_const(a.ptr, b.ptr, a.len);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare two chunks (given as pointers) for equality (useful as callback),
|
||||
* NULL chunks are never equal.
|
||||
|
||||
Reference in New Issue
Block a user