文字列比較の 2 つの異なる方法を理解するのに問題があります。2 つの文字列を比較する次の関数が与えられます。この関数は 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;
}
origin:オリジン スニペット
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()
ので、利点を理解できますか?
そして、一定時間アルゴリズムとはどういう意味ですか? 定数時間はリアルタイムとは何の関係もないと思いますか、それとも間違っているのでしょうか?