constantTimeEquals static method

bool constantTimeEquals(
  1. List<int> a,
  2. List<int> b
)

Compares a and b without an early exit on the first differing byte.

Use this when comparing a computed signature against one read from a file: a plain element-by-element comparison returns sooner for a nearly-correct guess, which leaks how much of the signature an attacker got right.

The comparison is constant-time only for equal-length inputs; a length mismatch is reported immediately, since the length is not a secret.

Implementation

static bool constantTimeEquals(List<int> a, List<int> b) {
  if (a.length != b.length) return false;
  var diff = 0;
  for (var i = 0; i < a.length; ++i) {
    diff |= a[i] ^ b[i];
  }
  return diff == 0;
}