Skip to content

Instantly share code, notes, and snippets.

@computator
Created August 8, 2018 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save computator/14ae9793c925506efc519dbd5494c5ba to your computer and use it in GitHub Desktop.
Save computator/14ae9793c925506efc519dbd5494c5ba to your computer and use it in GitHub Desktop.
Constant time string comparison function in PHP.
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