util: add constant-time is_zero_array function

This commit is contained in:
Jonas Nick
2024-09-25 16:03:14 +00:00
parent c8fbdb1b97
commit 0be79660f3
2 changed files with 29 additions and 0 deletions

View File

@@ -7467,6 +7467,18 @@ static void run_secp256k1_memczero_test(void) {
CHECK(secp256k1_memcmp_var(buf1, buf2, sizeof(buf1)) == 0);
}
static void run_secp256k1_is_zero_array_test(void) {
unsigned char buf1[3] = {0, 1};
unsigned char buf2[3] = {1, 0};
CHECK(secp256k1_is_zero_array(buf1, 0) == 1);
CHECK(secp256k1_is_zero_array(buf1, 1) == 1);
CHECK(secp256k1_is_zero_array(buf1, 2) == 0);
CHECK(secp256k1_is_zero_array(buf2, 1) == 0);
CHECK(secp256k1_is_zero_array(buf2, 2) == 0);
}
static void run_secp256k1_byteorder_tests(void) {
{
const uint32_t x = 0xFF03AB45;
@@ -7806,6 +7818,7 @@ int main(int argc, char **argv) {
/* util tests */
run_secp256k1_memczero_test();
run_secp256k1_is_zero_array_test();
run_secp256k1_byteorder_tests();
run_cmov_tests();

View File

@@ -239,6 +239,22 @@ static SECP256K1_INLINE int secp256k1_memcmp_var(const void *s1, const void *s2,
return 0;
}
/* Return 1 if all elements of array s are 0 and otherwise return 0.
* Constant-time. */
static SECP256K1_INLINE int secp256k1_is_zero_array(const unsigned char *s, size_t len) {
unsigned char acc = 0;
int ret;
size_t i;
for (i = 0; i < len; i++) {
acc |= s[i];
}
ret = (acc == 0);
/* acc may contain secret values. Try to explicitly clear it. */
acc = 0;
return ret;
}
/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. Both *r and *a must be initialized and non-negative.*/
static SECP256K1_INLINE void secp256k1_int_cmov(int *r, const int *a, int flag) {
unsigned int mask0, mask1, r_masked, a_masked;