secureEquals static method

bool secureEquals(
  1. String a,
  2. String b
)

Length-independent, content-constant-time comparison.

A plain == on the proof leaks how many leading bytes matched through timing, which is enough to forge one byte at a time.

Implementation

static bool secureEquals(String a, String b) {
  final x = utf8.encode(a);
  final y = utf8.encode(b);
  // Both proofs are fixed-width base64 digests, so the length is not itself
  // a secret — but folding it into `diff` rather than returning early keeps
  // the content comparison unconditional.
  var diff = x.length ^ y.length;
  final length = x.length < y.length ? x.length : y.length;
  for (var i = 0; i < length; i++) {
    diff |= x[i] ^ y[i];
  }
  return diff == 0;
}