Skip to content

Commit

Permalink
util: add constant-time is_zero_array function
Browse files Browse the repository at this point in the history
  • Loading branch information
jonasnick committed Oct 7, 2024
1 parent c8fbdb1 commit 0be7966
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down
16 changes: 16 additions & 0 deletions src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 0be7966

Please sign in to comment.