Skip to content

Commit 0be7966

Browse files
committed
util: add constant-time is_zero_array function
1 parent c8fbdb1 commit 0be7966

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

src/tests.c

+13
Original file line numberDiff line numberDiff line change
@@ -7467,6 +7467,18 @@ static void run_secp256k1_memczero_test(void) {
74677467
CHECK(secp256k1_memcmp_var(buf1, buf2, sizeof(buf1)) == 0);
74687468
}
74697469

7470+
7471+
static void run_secp256k1_is_zero_array_test(void) {
7472+
unsigned char buf1[3] = {0, 1};
7473+
unsigned char buf2[3] = {1, 0};
7474+
7475+
CHECK(secp256k1_is_zero_array(buf1, 0) == 1);
7476+
CHECK(secp256k1_is_zero_array(buf1, 1) == 1);
7477+
CHECK(secp256k1_is_zero_array(buf1, 2) == 0);
7478+
CHECK(secp256k1_is_zero_array(buf2, 1) == 0);
7479+
CHECK(secp256k1_is_zero_array(buf2, 2) == 0);
7480+
}
7481+
74707482
static void run_secp256k1_byteorder_tests(void) {
74717483
{
74727484
const uint32_t x = 0xFF03AB45;
@@ -7806,6 +7818,7 @@ int main(int argc, char **argv) {
78067818

78077819
/* util tests */
78087820
run_secp256k1_memczero_test();
7821+
run_secp256k1_is_zero_array_test();
78097822
run_secp256k1_byteorder_tests();
78107823

78117824
run_cmov_tests();

src/util.h

+16
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,22 @@ static SECP256K1_INLINE int secp256k1_memcmp_var(const void *s1, const void *s2,
239239
return 0;
240240
}
241241

242+
/* Return 1 if all elements of array s are 0 and otherwise return 0.
243+
* Constant-time. */
244+
static SECP256K1_INLINE int secp256k1_is_zero_array(const unsigned char *s, size_t len) {
245+
unsigned char acc = 0;
246+
int ret;
247+
size_t i;
248+
249+
for (i = 0; i < len; i++) {
250+
acc |= s[i];
251+
}
252+
ret = (acc == 0);
253+
/* acc may contain secret values. Try to explicitly clear it. */
254+
acc = 0;
255+
return ret;
256+
}
257+
242258
/** If flag is true, set *r equal to *a; otherwise leave it. Constant-time. Both *r and *a must be initialized and non-negative.*/
243259
static SECP256K1_INLINE void secp256k1_int_cmov(int *r, const int *a, int flag) {
244260
unsigned int mask0, mask1, r_masked, a_masked;

0 commit comments

Comments
 (0)