简体   繁体   English

Python中的哈希密码验证不起作用

[英]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. 因此,据我所知,它应该是相同的,第二段代码应该返回True。 However, it always comes out False. 但是,它总是错误的。 Any ideas? 有任何想法吗? (I'm using python 3.4.1) (我正在使用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. linecache.getline返回'\\n'字符。 https://docs.python.org/2/library/linecache.html 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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