ConstantTime

A plain PHP === comparison on two strings returns as soon as it finds a mismatched byte — for a public value that's fine, but for a secret (a token, an HMAC signature, a password reset code), how quickly a comparison fails leaks how many leading bytes an attacker guessed correctly. ConstantTime::equals() always takes the same amount of time regardless of where — or whether — the strings differ.

Method

ConstantTime::equals(string $known, string $user): bool
ConstantTime::equals('abc', 'abc'); // true
ConstantTime::equals('abc', 'abd'); // false — same timing either way

A thin wrapper over PHP's own hash_equals(). Used internally by Csrf's token comparison and HMAC::verify().

Next steps

  • HMAC — verifies signatures using this under the hood.
  • Csrf — compares session-backed tokens using this.