随机睡眠可以防止定时攻击吗?当您可以正确解决问题时,为什么要打扰睡眠般的黑客攻击?
2022-08-30 23:01:33
						来自维基百科
在密码学中,定时攻击是一种侧信道攻击,攻击者试图通过分析执行加密算法所需的时间来破坏密码系统。
实际上,为了防止定时攻击,我使用以下从这个答案中获取的函数:
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));
这种方法完全可以防止定时攻击吗?或者只是让工作更努力?