来自维基百科
在密码学中,定时攻击是一种旁道攻击,其中攻击者试图通过分析执行密码算法所花费的时间来破坏密码系统。
实际上,为了防止定时攻击,我使用了从这个答案中获取的以下函数:
function timingSafeCompare($safe, $user) {
// Prevent issues if string length is 0
$safe .= chr(0);
$user .= chr(0);
$safeLen = strlen($safe);
$userLen = strlen($user);
// Set the result to the difference between the lengths
$result = $safeLen - $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($safe[$i % $safeLen]) ^ ord($user[$i]));
}
// They are only identical strings if $result is exactly 0...
return $result === 0;
}
但我在想是否可以使用随机睡眠来防止这种攻击
function timingSafeCompare($a,$b) {
sleep(rand(0,100));
if ($a === $b) {
return true;
} else {
return false;
}
}
或者也许增加睡眠的随机性
sleep(rand(1,10)+rand(1,10)+rand(1,10)+rand(1,10));
这种方法可以完全防止定时攻击吗?还是只是让工作更加努力?