3

Using the Windows cryptography API, how do I compare two byte arrays for equality in constant time?

Edit: The length of the secret is fixed and is public knowledge.

Demi
  • 3,535
  • 5
  • 29
  • 45

1 Answers1

2

Timing safe comparison requires knowing which array is coming from the user (which determines the time it will take), and which array is your secret (which you don't want to give away the secret of how long it is)

//Code released into public domain. No attribution required.
Boolean TimingSafeArrayCompare(Byte[] safe, Byte[] user)
{
   /*
      A timing safe array comparison.

      To prevent leaking length information,  
      it is important that user input is always used as the second parameter.

         safe: The internal (safe) value to be checked
         user: The user submitted (unsafe) value

      Returns True if the two arrays are identical.
   */
   int safeLen = safe.Length;
   int userLen = user.Length;

   // Set the result to the difference between the lengths.
   // This means that arrays of different length will already cause nDiff to be non-zero
   int nDiff = safeLen - userLen;

   // Note that we ALWAYS iterate over the user-supplied length
   // This is to prevent leaking length information
   for (i = 0 to userLen-1)
   {
      //Using mod here is a trick to prevent leaking.
      //It's safe, since if the lengths are different, nDiff will already be non-zero
      nDiff = nDiff | ( User[i] xor Safe[i mod safeLen] );
   }

   // They are only identical strings if nDiff is exactly zero
   return (nDiff == 0);
}

It's an ingenious technique, that i first saw here.

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
  • I think the code has some errors. Syntactically because braces don't match and then secondly, why add 1 to the index? You are not comparing the first byte that way – Paul Bastian Dec 20 '15 at 17:49
  • @PaulBastian It was transcribed from Delphi, in my head, where strings start their indexing at `1`. The code, as provided, is in no specific language, and requires the reader to adapt the algorithm to their specific language. – Ian Boyd Dec 21 '15 at 16:44