简体   繁体   中英

Hashed password authentication in Python not working

I have this code which salts the user's input, hashes it and writes the hash and the salt to a file:

def newhash(input):
    salt = uuid.uuid4().hex
    saltin = input + salt
    hashed_in = (hashlib.sha256(saltin.encode()).hexdigest())
    file.write(str(hashed_in) + '\n')
    file.write(str(salt) + '\n')
    file.close()

Then, I use this code to salt and hash the user's new input (using the same salt) and compare it to the one in the file.

salt = linecache.getline(userin + '.userdat', 2)
saltin = newin + salt
hashed_newin = (hashlib.sha256(saltin.encode()).hexdigest())
realin = linecache.getline('file.dat', 1)
if hashed_newin == realin:
    return True

The new input is salted using the same salt and hashed using the same function. So, as far as I know, it should come out the same and the second piece of code should return True. However, it always comes out False. Any ideas? (I'm using python 3.4.1)

EDIT: Ran the code through the debugger one more time. Turns out the new hash comes out different for some reason.

linecache.getline returns '\\n' character. https://docs.python.org/2/library/linecache.html

This code should work:

salt = linecache.getline(userin + '.userdat', 2).strip()
saltin = newin + salt
hashed_newin = (hashlib.sha256(saltin.encode()).hexdigest())
realin = linecache.getline('file.dat', 1).strip()
if hashed_newin == realin:
    return True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM