6

Heres my code:

import hashlib

real = hashlib.sha512("mom")

status = True

while status:
    inp = raw_input("What's the password?")
    converted = hashlib.sha512(inp)

    if converted == real:
        print "Access granted!"
        status = False
    else:
        print "Access denied."

I'm new to hashlib, and I'm just playing around with it. What I thought this would do is validate the users input to the hash of the actual password, however if you enter the correct password, it still comes up "Access denied." Can anyone point me in the right direction?

ElefantPhace
  • 3,743
  • 3
  • 18
  • 36

3 Answers3

13

You're comparing two hash objects instead of just comparing their digests.

Change your if to if converted.digest() == real.digest() and that should work.

By doing if converted == real you're actually comparing the two objects, which while they represent a hash object that does hash to the same thing, they are different objects and since hashlib hash objects don't implement __cmp__, __eq__, or __ne__, they fall back to comparing the two objects by identity, which since they are two distinct objects, will return false.

From the doc link:

If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity (“address”).

You can see that those objects don't implement those operators by doing a dir() on them:

>>> test = hashlib.sha512('test')
>>> dir(test)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__',
 '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
 '__sizeof__', '__str__', '__subclasshook__', 'block_size', 'copy', 'digest',
 'digest_size', 'digestsize', 'hexdigest', 'name', 'update']
Daniel DiPaolo
  • 51,147
  • 13
  • 111
  • 112
4

If you compare the digests, that should work:

if converted.digest() == real.digest():
   ...
NPE
  • 438,426
  • 93
  • 887
  • 970
2

You are creating two different hashlib objects and they are not equal. What you need is to compare the digest:

if converted.digest() == real.digest():
deStrangis
  • 1,842
  • 1
  • 19
  • 24