To compare two strings, I currently use strcmp or one of its variants. However, because strcmp take longer if more characters match, it is vulnerable to timing attacks. Is there a constant-time string comparison function in the standard library on Windows?
Asked
Active
Viewed 926 times
1
-
Limit the maximum string length and pad with zeroes while accumulating the differences in a fixed loop perhaps? Or I suppose you might try computing a cryptographic hash digest of the strings and comparing that instead, so as not to give away sideband information about the contents of pre-calculated database keys. I don't know how to effectively cancel the cache/paging effects of rare strings on Windows though. – doynax Jul 25 '17 at 18:07
1 Answers
-1
I don't think Windows nor Visual Studio has such functions.
At least for something simple like strcmp you can whip something up yourself.
If you only care about equality:
int strctcmp(const char*a, const char*b)
{
int r = 0;
for (; *a && *b; ++a, ++b)
{
r |= *a != *b;
}
return r;
}
If you need sortable results and you need to process all of the longest string:
int strctcmp(const char*a, const char*b)
{
int r = 0, c;
for (;;)
{
c = *a - *b;
if (!r) r = c;
if (!*a && !*b) break;
if (*a) ++a;
if (*b) ++b;
}
return r;
}
These are not perfect timing wise but should be more than good enough for anything network based.

Anders
- 97,548
- 12
- 110
- 164