tags:

views:

71

answers:

1

In the tornado.web module there is a function called _time_independent_equals:

def _time_independent_equals(a, b):
    if len(a) != len(b):
        return False
    result = 0
    for x, y in zip(a, b):
        result |= ord(x) ^ ord(y)
    return result == 0

It is used to compare secure cookie signatures, and thus the name.

But regarding the implementation of this function, is it just a complex way to say a==b?

+8  A: 

That function does not simply compare the strings, it tries to always take the same amount of time to execute.

This is useful for security tasks like comparing passwords. If the function returned on the first mismatching byte, an attacker could try all possible first bytes and know that the one that takes longest is a match. Then they could try all possible second bytes and know that the one that takes longest is a match. This can be repeated until the entire string is deduced. (In reality you have to do a lot of averaging to overcome random delays in the network, but it works if you are patient.)

Daniel Newby