I'm implementing a token system in a nodeJS app where I need to check the equality of two strings that have been hashed using SHA256. My initial idea was that I can simply test equality using a strict equal operator (hash1 === hash2
) because digests should produce the same string if they had the same input. However, I've seen an article from Paragon Initiative claiming it's safer to compare the strings using bitwise operators on each character's ascii code.
To compare the digest tokens, the Paragon code uses the following code snippet (PHP):
public static function hash_equals($hash1, $hash2)
...
$res = 0;
$len = \strlen($hash1);
for ($i = 0; $i < $len; ++$i) {
$res |= \ord($hash1[$i]) ^ \ord($hash2[$i]);
}
return $res === 0;
}
Basically, the characters at each index using a bitwise XOR and then saved to a flag value using a bitwise OR. If any of the characters mismatch, then the difference is saved in $res
.
Is this any more effective than using a strict string comparison? Hash digests are just strings and I don't know why a simple string comparison would be less effective than explicitly checking every sing byte in the strings.
Article Ref: https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence Code Ref: https://github.com/psecio/gatekeeper/blob/7b8ec374e208148692316a34c1b4700d5407ef9b/src/Psecio/Gatekeeper/Gatekeeper.php
via Copernicus
No comments:
Post a Comment