Skip to content

Instantly share code, notes, and snippets.

@KaiserWerk
Last active March 2, 2018 15:16
Show Gist options
  • Save KaiserWerk/ccc76e5d0e1694afabdfbd705d96e6a2 to your computer and use it in GitHub Desktop.
Save KaiserWerk/ccc76e5d0e1694afabdfbd705d96e6a2 to your computer and use it in GitHub Desktop.
Function for comparing two strings in a way timing attacks won't work
<?php
/*
* Make sure $compare_length is greater than (or equal to) the maximum length of
* both $string1 and $string2
*
* It's a user setting so different maximum lengths can be handled.
*
* Edit: the built-in PHP function hash_equals might me worth a look:
* http://php.net/manual/de/function.hash-equals.php
*/
function str_cmp_sec($string1, $string2, $compare_length = 100)
{
if(strlen($string1) != strlen($string2)) {
return false;
}
$str1_parts = str_split(str_pad((string)$string1, $compare_length, '0', STR_PAD_RIGHT));
$str2_parts = str_split(str_pad((string)$string2, $compare_length, '0', STR_PAD_RIGHT));
$result_array = array();
$i = 0;
foreach ($str1_parts as $part) {
if ($part === $str2_parts[$i]) { // also see str_cmp() and similar_text()
$result_array[$i] = true;
} else {
$result_array[$i] = false;
}
++$i;
}
return (bool)array_product($result_array);
}
var_dump(str_cmp_sec('hallo', 'hello')); // bool(false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment