Constant-time string comparison function

1k Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.