Hashlib 哈希值无法正确比较
这是我的代码:
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."
我是 hashlib 的新手,我只是在玩它。我认为这会验证用户输入的实际密码的哈希值,但是如果您输入正确的密码,它仍然会出现“访问被拒绝”。有人能指出我正确的方向吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果你比较摘要,那应该有效:
If you compare the digests, that should work:
您正在创建两个不同的 hashlib 对象,并且它们不相等。您需要的是比较摘要:
You are creating two different hashlib objects and they are not equal. What you need is to compare the digest:
您正在比较两个哈希对象,而不仅仅是比较它们的摘要。
将您的
if
更改为if conversion.digest() == real.digest()
,这应该可以工作。通过执行
if conversion == real
你实际上是在比较两个对象,虽然它们代表一个散列到同一事物的散列对象,但它们是不同的对象,并且由于hashlib
code> 哈希对象不实现__cmp__
、__eq__
或__ne__
、他们会根据身份比较两个对象,因为它们是两个不同的对象,所以将返回 false 。从文档链接:
您可以看到这些对象没有通过对它们执行
dir()
来实现这些运算符:You're comparing two hash objects instead of just comparing their digests.
Change your
if
toif 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 sincehashlib
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:
You can see that those objects don't implement those operators by doing a
dir()
on them: