Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compare two strings via calculating xor of their characters?

Some time ago I found this function (unfortunately, I don't remember from where it came from, most likely from some Python framework) that compares two strings and returns a bool value. It's quite simple to understand what's going on here. Finding xor between char returns 1 (True) if they do not match.

def  cmp_strings(str1, str2):
    return len(str1) == len(str2) and sum(ord(x)^ord(y) for x, y in zip(str1, str2)) == 0

But why is this function used? Isn't it the same as str1==str2?

like image 327
funnydman Avatar asked Dec 24 '19 12:12

funnydman


People also ask

How do you use XOR 2 strings?

Approach: The idea is to iterate over both the string character by character and if the character mismatched then add “1” as the character in the answer string otherwise add “0” to the answer string to generate the XOR string.

How do you compare strings and characters?

The compare() function in C++ The compare() function compares two strings and returns the following values according to the matching cases: Returns 0, if both the strings are the same. Returns <0, if the value of the character of the first string is smaller as compared to the second string input.

How do you compare characters in two strings?

We compare the strings by using the strcmp() function, i.e., strcmp(str1,str2). This function will compare both the strings str1 and str2. If the function returns 0 value means that both the strings are same, otherwise the strings are not equal.

What happens when you compare two string objects with the operator?

Important points about String comparison 1) You can compare two String variable using == operator but you should never do this because it will return true if you compare String literals but return false if you compare String object to a literal or two String object, even if they have same characters.


1 Answers

It takes a similar amount of time to compare any strings that have the same length. It's used for security when the strings are sensitive. Usually it's used to compare password hashes.

If == is used, Python stops comparing characters when the first one not matching is found. This is bad for hashes because it could reveal how close a hash was to matching. This would help an attacker to brute force a password.

This is how hmac.compare_digest works.

like image 50
Anonymous Avatar answered Oct 06 '22 03:10

Anonymous