util: add function for constant-time memory comparison

Add a function to check if two buffers of the same length contain the
same data, but do the comparison in a constant time with respect to the
returned value to avoid creating a timing side channel, i.e. the time
depends only on the buffer length, not on the content.

Use the gnutls_memcmp() or nettle_memeql_sec() functions if available,
otherwise use the same algorithm as nettle - bitwise ORing XORed data.
This commit is contained in:
Miroslav Lichvar
2025-04-02 15:32:05 +02:00
parent dd8738119b
commit dab98fa8da
4 changed files with 47 additions and 1 deletions

5
util.h
View File

@@ -257,6 +257,11 @@ extern unsigned int UTI_HexToBytes(const char *hex, void *buf, unsigned int len)
number of pointers to the words. */
extern int UTI_SplitString(char *string, char **words, int max_saved_words);
/* Check if two buffers of the same length contain the same data, but do the
comparison in constant time with respect to the returned value to avoid
creating a timing side channel */
extern int UTI_IsMemoryEqual(const void *s1, const void *s2, unsigned int len);
/* Macros to get maximum and minimum of two values */
#ifdef MAX
#undef MAX