I have to create an API that authenticates a request by checking if the token in the request is equal to the valid token stored in our database. Initially I used the ==
operator to compare the two tokens, but then I learned that this was vulnerable to a timing attack.
So I wrote the below code in C# to do the token comparison:
static bool constantTimeStringCompare(string a, string b)
{
if (a.Length != b.Length)
{
return false;
}
int result = 0;
for (int i =0; i < a.Length; i++)
{
result |= a[i] ^ b[i];
}
if (result == 0)
{
return a == b;
} else
{
return false;
}
}
Since I am paranoid about "rolling my own crypto" I added the check at the end of the function that does the naïve string comparison to double check that the tokens really are the same. Does doing this open me up to a timing attack? I don't think it does, as the naïve string comparison only gets run if the xor check thinks the two strings are the same, which will only happen if they really are the same or if there is a really rare bug in the code -- the upshot is that it will rarely get run, thus the running time of the function will be constant.
Personally I think it's a bad idea for me to be doing this (we should be using client certificates), but my company doesn't care.