【发布时间】:2013-09-20 11:50:04
【问题描述】:
我很难理解两种不同的字符串比较方式。给出了以下比较两个字符串的函数。 该函数用于 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() 做正确的工作,所以我可以理解优势?
恒定时间算法是什么意思?我认为 constant-time 与实时无关,或者如果我错了?
【问题讨论】:
标签: php algorithm comparison