来自维基百科
时序攻击(Timing attack)是密码学中的一种侧信道攻击,攻击者尝试通过分析加密算法执行所需的时间来破解加密系统。
实际上,为了防止时序攻击,我正在使用从这个回答中提取出来的以下函数:
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;
}
但我在想,如果使用随机的延迟,是否有可能防止这种攻击,比如:
But I was thinking if is possible prevent this kind of attack using a random sleep like
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));
这种做法能完全防止时序攻击吗?还是只是让攻击变得更困难了?
hash_equals()
,然后结束它。 - Scott Arciszewski