znk3r / hash_equals

A compatibility library for hash_equals() to avoid timing attacks
MIT License
1 stars 0 forks source link

Why do you only test the beginning of a string? #1

Open rugk opened 8 years ago

rugk commented 8 years ago

Here you determinate which string is shorter and only compare the shorter part? 😯

When the string length is different the comparison should always fail!

znk3r commented 8 years ago

Hi. If the lengths are different will always fail, because the initial value on $result will be different from 0.

rugk commented 8 years ago

Still a strange implementation. You could just strllen the variables and compare them.

znk3r commented 8 years ago

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.

rugk commented 8 years ago

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