且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

安全字符串比较功能

更新时间:2023-02-03 08:29:25

试图阻止定时攻击


In cryptography, a timing attack is a side channel attack in which the attacker attempts to compromise a cryptosystem by analyzing the time taken to execute cryptographic algorithms. Every logical operation in a computer takes time to execute, and the time can differ based on the input; with precise measurements of the time for each operation, an attacker can work backwards to the input.

基本上,如果需要不同的金额的时间来比较正确的密码和不正确的密码,那么您可以使用时间来确定您正确猜测的密码的字符数。

Basically, if it takes a different amount of time to compare a correct password and an incorrect password, then you can use the timing to figure out how many characters of the password you've guessed correctly.

非常有缺陷的字符串比较(这基本上是正常的字符串相等函数,添加了明显的 wait ):

Consider an extremely flawed string comparison (this is basically the normal string equality function, with an obvious wait added):

function compare(a, b) {
    if(len(a) !== len(b)) { 
        return false;
    }
    for(i = 0; i < len(a); ++i) {
        if(a[i] !== b[i]) {
            return false;
        }
        wait(10); // wait 10 ms
    }
    return true;
}

假设您输入密码,一个密码,另一个大约10毫秒。这告诉你什么?

Say you give a password and it (consistently) takes some amount of time for one password, and about 10 ms longer for another. What does this tell you? It means the second password has one more character correct than the first one.

这可让您进行电影黑客 - 您一次猜测一个密码一个字符比猜测每一个可能的密码容易得多)。

This lets you do movie hacking -- where you guess a password one character at a time (which is much easier than guessing every single possible password).

在现实世界中,还有其他因素,所以你必须尝试密码多次,多次处理随机性的现实世界,但你仍然可以尝试每一个字符的密码,直到明显需要更长的时间,然后开始两个字符的密码,等等。

In the real world, there's other factors involved, so you have to try a password many, many times to handle the randomness of the real world, but you can still try every one character password until one is obviously taking longer, then start on two character password, and so on.

仍然有一个小问题:

if(strlen($a) !== strlen($b)) { 
    return false;
}

它允许您使用定时攻击来找出正确的密码长度,这使您不必费心猜测任何更短或更长的密码。一般来说,您希望首先哈希您的密码(这将创建等长字符串),所以我猜他们没有考虑到它是一个问题。

It lets you use timing attacks to figure out the correct length of the password, which lets you not bother guessing any shorter or longer passwords. In general, you want to hash your passwords first (which will create equal-length strings), so I'm guessing they didn't consider it to be a problem.