Request for Comments: Timing attack safe string comparison function


Timing attacks are not a widely recognized problem, since they require significant skill and resources of the attacker. To prevent these attacks constant-time string comparisons can be used. These implementations are rather hard to get right, without leaking timing information.

While high profile applications and frameworks already ship with time-constant string comparison functions, this RFC aims to make it simpler for PHP developers to protect their applications. Additionally there's less chance of unexpected timing differences in lower level languages.

The password_verify function implemented in PHP 5.5 already does a time-constant string comparison, however in many projects bcrypt can not be used for some reason (legacy project, interfacing with other systems, etc.), but they'd still benefit from this functionality.


Implement a new function called hash_compare as part of ext/hash.

Signature bool hash_compare(string knownString, string userString)

The time this function takes is based only on the length of the user supplied string.

Users have to be mindful, as it is important that the user supplied string (or a hash of that string) is used as the the second parameter not the first.

Backward Incompatible Changes


Proposed PHP Version(s)

Next PHP 5.x

Impact to Existing Extensions


Patches and Tests


Timing attack safe string comparison function
Real name Yes No
ajf (ajf)  
andrey (andrey)  
brianlmoon (brianlmoon)  
bwoebi (bwoebi)  
chregu (chregu)  
cpriest (cpriest)  
datibbaw (datibbaw)  
derick (derick)  
indeyets (indeyets)  
klaussilveira (klaussilveira)  
krakjoe (krakjoe)  
lstrojny (lstrojny)  
malukenho (malukenho)  
mariuz (mariuz)  
nikic (nikic)  
pajoye (pajoye)  
pollita (pollita)  
seld (seld)  
shm (shm)  
stas (stas)  
treffynnon (treffynnon)  
yohgaki (yohgaki)  
zhangzhenyu (zhangzhenyu)  
Final result: 22 1
This poll has been closed.



  • 0.1 Initial publication
  • 0.2 Renamed to hash_compare, added link to Zend Framework 2, removed information leak when knownString is empty (Thank you Tjerk)
  • 1.0 Moved function to ext/hash. Started voting.
  • 1.1 Added section about differences between RFC and implementation

Differences between this RFC and the implementation

  • The function is now called hash_equals
  • Both arguments passed to the function have to be strings, otherwise an E_WARNING is raised.
rfc/timing_attack.txt · Last modified: 2017/09/22 13:28 by