Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "&=" operator and why does Twilio use it when comparing strings?

What is &= in python?

For example:

for c1, c2 in izip(string1, string2):
    result &= c1 == c2

I found it in the twilio python library: https://github.com/twilio/twilio-python/blob/master/twilio/util.py#L62

Why don't they just compare the strings directly return string1 == string2 and compare each character?

like image 529
Michael Avatar asked Sep 26 '14 19:09

Michael


1 Answers

See the secure_compare doctring:

Compare two strings while protecting against Timing Attacks

By forcing evaluation of every character an attacker can't use the time it took to guess where the difference occurred - with a "normal" implementation that returned immediately on the first difference, this would be possible.

The semantic counter to result &= c1 == c2 (succeed when they are all the same) is actually return c1 != c2 (fail/abort on the first difference), and not the proposed condition the question.

Now, result &= c1 == c2 is the same as result = result & (c1 == c2), where & (also known as a bitwsie-AND) is a strict logical-AND over Booleans. This means that the use of the result accumulator will remain True if and only if the result was previously True and the compassion is also True.

like image 175
user2864740 Avatar answered Nov 04 '22 04:11

user2864740