Open rugk opened 8 years ago
Hi. If the lengths are different will always fail, because the initial value on $result
will be different from 0.
Still a strange implementation. You could just strllen the variables and compare them.
The purpose of this algorithm is to provide a constant comparison (or as constant as possible), trying to avoid giving information about the length/contents with string comparison optimisations. So we want to prevent:
The traditional comparison operator already applies those optimisations on a byte level, but that's not desirable to avoid timing attacks comparing hashes.
Actually
Comparing both lengths and returning if the length doesn't match before actually comparing.
is not a bad thing. The original hash_equals
and other implementations such as Libsodiums one (PHP binding here) also do it this way. If the size is different, it can be checked in a fast way.
What matters is to hide the content of a string/.., not the length.
Additionally the length is always exposed to an attacker as it takes a different time to compare a short string than a longer one.
See also https://stackoverflow.com/questions/18508026/when-preventing-timing-attacks-is-it-safe-to-exit-on-different-lengths
Here you determinate which string is shorter and only compare the shorter part? 😯
When the string length is different the comparison should always fail!