0

I'm trying to create a simple software that includes the user having a password. I thought that instead of saving the password in the code as text, maybe try to learn a bit about how hashing works. I then tried to use the hashlib library for python. To me this code should be able to see that the passwords x and y match and therefore continue the hypothetical "login", but for some reason it doesn't do what I want it to do. Is there a syntax error? does password matching work in a different way? I need help to make the software compare 2 hashes and therefore login.

import hashlib

pw1=hashlib.md5(input("please enter your password").encode('utf-8'))
pw2=hashlib.md5(input("please re-enter your password").encode('utf-8'))

if pw1.hexdigest == pw2.hexdigest:
    print("Success. Passwords match")
if pw1.hexdigest != pw2.hexdigest:
    print("Failure. Passwords do not match")
  • 1
    For password hashing, this [thread](https://stackoverflow.com/questions/9594125/salt-and-hash-a-password-in-python) is a useful starting point. Note that using md5sum is not a good/secure way to hash a password, and in that thread there are more detailed explanations on what is done and how to do this in a more secure manner. – metatoaster Mar 06 '19 at 02:02
  • @metatoaster Thanks! The thread is really helpful regarding ways to hash a passwords, but so are many others that I've read that talk mainly about why md5 is bad or why bcrypt is good, but I guess I'm stuck on a much earlier step, I used md5 just because it popped into my mind and wont actually do so when writing the software itself. However I still can't understand why python doesn't compare hashes the way I thought they would. – Giovanni Magdy Mar 06 '19 at 02:16

1 Answers1

1

The hexdigest part of a hashlib instance is the function itself. You must call it:

hex1 = pw1.hexdigest()
hex2 = pw2.hexdigest()

for instance. Now you can compare the two strings hex1 and hex2.

(As metatoaster said in a comment, don't use md5.)

Note, by the way, that pw1 and pw2 are instances of hashers: you can feed them more data. In this case it doesn't make sense to do so, but:

pw1.update(b'more data')

modifies what the next call to pw1.hexdigest() returns.

torek
  • 448,244
  • 59
  • 642
  • 775
  • I've tried declaring the 2 vars you said and then comparing them in the if conds. instead of pw1.hexdigest(), but it still wouldnt work. Please excuse me if I misunderstood. Edit: I made a syntax error. Never mind it works perfectly. Thanks alot! – Giovanni Magdy Mar 06 '19 at 02:25
  • Another side note: You don't *need* the variables—you can call `hexdigest()` over and over again if you like—but I think it's clearer with them. – torek Mar 06 '19 at 02:30