Skip to content

Instantly share code, notes, and snippets.

@levigross
Created May 2, 2011 02:03
Show Gist options
  • Save levigross/951097 to your computer and use it in GitHub Desktop.
Save levigross/951097 to your computer and use it in GitHub Desktop.
Safe hash comparison
from itertools import izip
def compare_hash(hashone,hashtwo):
if len(hashone) == len(hashtwo): # Every hash should be the same length
if sum((ord(o) ^ ord(t) for o,t in izip(hashone,hashtwo))):
return False
else:
return True
else:
return False
@treystout
Copy link

Any time you find yourself doing "if statement: return True else: return False" just return the statement. For example line 4 could be:

return sum((ord(o) ^ ord(t) for o,t in izip(hashone,hashtwo))) == 0

Or even more simply the whole thing is an and of two booleans: so

def compare_hash(hashone, hashtwo):
  return len(hashone) == len(hashtwo) and sum((ord(o) ^ ord(t) for o,t in izip(hashone,hashtwo))) == 0

@levigross
Copy link
Author

I agree, I just wrote this in a verbose manner so people will understand the goal behind the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment