我很难理解两种不同的字符串比较方式。给出了以下比较两个字符串的函数。该函数用于 Symfony-Framework 安全组件中,用于比较用户登录过程中的密码。
/**
* Compares two strings.
*
* This method implements a constant-time algorithm to compare strings.
*
* @param string $knownString The string of known length to compare against
* @param string $userInput The string that the user can control
*
* @return Boolean true if the two strings are the same, false otherwise
*/
function equals($knownString, $userInput)
{
// Prevent issues if string length is 0
$knownString .= chr(0);
$userInput .= chr(0);
$knownLen = strlen($knownString);
$userLen = strlen($userInput);
$result = $knownLen - $userLen;
// Note that we ALWAYS iterate over the user-supplied length
// This is to prevent leaking length information
for ($i = 0; $i < $userLen; $i++) {
// Using % here is a trick to prevent notices
// It's safe, since if the lengths are different
// $result is already non-0
$result |= (ord($knownString[$i % $knownLen]) ^ ord($userInput[$i]));
}
// They are only identical strings if $result is exactly 0...
return 0 === $result;
}
起源:起源片段
我很难理解equals()
函数和简单比较之间的区别===
。我写了一个简单的工作示例来解释我的问题。
给定字符串:
$password1 = 'Uif4yQZUqmCWRbWFQtdizZ9/qwPDyVHSLiR19gc6oO7QjAK6PlT/rrylpJDkZaEUOSI5c85xNEVA6JnuBrhWJw==';
$password2 = 'Uif4yQZUqmCWRbWFQtdizZ9/qwPDyVHSLiR19gc6oO7QjAK6PlT/rrylpJDkZaEUOSI5c85xNEVA6JnuBrhWJw==';
$password3 = 'iV3pT5/JpPhIXKmzTe3EOxSfZSukpYK0UC55aKUQgVaCgPXYN2SQ5FMUK/hxuj6qZoyhihz2p+M2M65Oblg1jg==';
示例 1(按预期操作)
echo $password1 === $password2 ? 'True' : 'False'; // Output: True
echo equals($password1, $password2) ? 'True' : 'False'; // Output: True
示例 2(按预期操作)
echo $password1 === $password3 ? 'True' : 'False'; // Output: False
echo equals($password1, $password3) ? 'True' : 'False'; // Output: False
我阅读了有关Karp Rabin Algorithm的信息,但我不确定该equals()
函数是否代表Karp Rabin Algorithm,而且总的来说我不理解维基百科的文章。
另一方面,我读到该equals()
功能将防止暴力攻击,对吗?有人能解释一下有什么好处equals()
吗?或者有人可以给我一个例子,哪里===
会失败并且equals()
做正确的工作,所以我可以理解优势?
恒定时间算法是什么意思?我认为常数时间与实时无关,或者如果我错了?