Dart constant string comparison

I am implementing a github push call listener in dart and I found this document: https://developer.github.com/webhooks/securing/

where he wrote:

The plain == operator is deprecated. A method like secure_compare performs constant-time string comparisons, which makes it safe against certain temporary attacks against the regular equality operators.

I need to compare 2 hashes for equality. Now I was wondering if there is a way to compare a string at constant time in a dart? (read: is there a function to compare the time of a constant string in a dart?)

+3


source to share


1 answer


the standard implementation is not constant time, but you can simply create your own comparison function that compares each block of code in a String and doesn't short-circuit:

bool secureCompare(String a, String b) {
  if(a.codeUnits.length != b.codeUnits.length)
    return false;

  var r = 0;
  for(int i = 0; i < a.codeUnits.length; i++) {
    r |= a.codeUnitAt(i) ^ b.codeUnitAt(i);
  }
  return r == 0;
}

      



This function will perform constant time when the String is compared if the two input strings are the same length. Since you are comparing hashes this shouldn't be a problem, but for variable length strings this method will still contain sync time information because it returns immediately if the lengths are not equal.

+4


source







All Articles