diff --git a/src/libsodium/include/sodium/utils.h b/src/libsodium/include/sodium/utils.h index bb42c0c6..e61f9b34 100644 --- a/src/libsodium/include/sodium/utils.h +++ b/src/libsodium/include/sodium/utils.h @@ -40,6 +40,9 @@ int sodium_compare(const unsigned char *b1_, const unsigned char *b2_, size_t len) __attribute__ ((warn_unused_result)); +SODIUM_EXPORT +int sodium_is_zero(const unsigned char *n, const size_t nlen); + SODIUM_EXPORT void sodium_increment(unsigned char *n, const size_t nlen); diff --git a/src/libsodium/sodium/utils.c b/src/libsodium/sodium/utils.c index e013c788..a032219e 100644 --- a/src/libsodium/sodium/utils.c +++ b/src/libsodium/sodium/utils.c @@ -154,6 +154,31 @@ sodium_compare(const unsigned char *b1_, const unsigned char *b2_, size_t len) return (int) (gt + gt + eq) - 1; } +int +sodium_is_zero(const unsigned char *n, const size_t nlen) +{ + size_t i; + unsigned char c = 0U; + + for (i = (size_t) 0U; i < nlen; i++) { + c |= n[i]; + } + return ((c - 1U) >> 8) & 1U; +} + +void +sodium_increment(unsigned char *n, const size_t nlen) +{ + size_t i; + unsigned int c = 1U << 8; + + for (i = (size_t) 0U; i < nlen; i++) { + c >>= 8; + c += n[i]; + n[i] = (unsigned char) c; + } +} + /* Derived from original code by CodesInChaos */ char * sodium_bin2hex(char * const hex, const size_t hex_maxlen, @@ -568,16 +593,3 @@ sodium_mprotect_readwrite(void *ptr) { return _sodium_mprotect(ptr, _mprotect_readwrite); } - -void -sodium_increment(unsigned char *n, const size_t nlen) -{ - size_t i; - unsigned int c = 1U << 8; - - for (i = (size_t) 0U; i < nlen; i++) { - c >>= 8; - c += n[i]; - n[i] = (unsigned char) c; - } -} diff --git a/test/default/sodium_utils.c b/test/default/sodium_utils.c index 7a19261a..9fc74273 100644 --- a/test/default/sodium_utils.c +++ b/test/default/sodium_utils.c @@ -105,5 +105,13 @@ int main(void) (unsigned int) bin_len); } } + memset(buf1, 0, sizeof buf1); + if (sodium_is_zero(buf1, sizeof buf1) != 1) { + printf("sodium_is_zero() failed\n"); + } + buf1[randombytes_uniform(sizeof buf1)]++; + if (sodium_is_zero(buf1, sizeof buf1) != 0) { + printf("sodium_is_zero() failed\n"); + } return 0; }