Created
August 8, 2018 03:57
-
-
Save computator/14ae9793c925506efc519dbd5494c5ba to your computer and use it in GitHub Desktop.
Constant time string comparison function in PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function const_time_strcmp($a, $b) { | |
// inputs must be strings | |
if(!is_string($a) || !is_string($b)) | |
return false; | |
// strings must be the same length | |
if(strlen($a) !== strlen($b)) | |
return false; | |
// result will be all zero if values are equal | |
$c = $a ^ $b; | |
// add up the byte values. if result is zero then strings are identical | |
return array_sum(array_map('ord', str_split($c))) === 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment