【问题标题】:Comparing 2 hash values returning False even though they are the same比较 2 个返回 False 的哈希值,即使它们相同
【发布时间】:2021-12-22 23:48:11
【问题描述】:

程序的工作原理是用户发送 2 个输入(用户输入和密码输入)。 这些将与文本文件的文件名(即用户名)和上下文(即散列密码)进行比较。密码输入被散列并返回与散列后的原始密码相同,没有差异,但是当我与 if 语句进行比较时,它返回 False。这是我的代码:

import os
import hashlib

username = "coolcat"
password = "my secret password!!"

result = hashlib.sha1(password.encode("utf-8"))

if not os.path.exists(f"{username}.txt"):
    open(f"{username}.txt", 'w').close()
with open(f"{username}.txt", "w") as file:
   file.write(str(result.digest()))

userinput = input("Your username please : ")
passwordinput = input("Your password please : ")
resulte = hashlib.sha1(passwordinput.encode("utf-8"))
print(str(resulte.digest()))
try :
    with open(f"{userinput}.txt", "r") as file:
        hashed = file.read()
    print(hashed)

    if hashed == resulte.digest():
        print("Access Granted")
    if hashed != resulte.digest():
        print("Wrong password!!")
except FileNotFoundError :
    print("Username not found!!1!")

【问题讨论】:

  • 我建议你打印你比较的参数的类型......这可能会给你答案
  • hashed == resulte.digest() 你将字符串与字节进行比较,这将始终是False
  • 不确定,但尝试查看从文件读取时是否没有收到\n
  • 一些旁注:不需要if not os.path.exists 部分 - 当使用'w' 打开文件时,如果文件不存在,则会创建该文件。您可以将整个 if hashed != resulte.digest(): 行替换为简单的 else:...
  • 谢谢!!将 resulte.digest() 包裹在 str 周围是有效的。

标签: python hashlib


【解决方案1】:

您在这里使用str 打印东西是自欺欺人。问题是 hash 是 Unicode 字符串,resulte.digest() 是字节字符串。它们都打印相同,因为您使用str 函数来转换它们。如果你有字节字符串b'abc',它包含三个字节,并且你调用str(b'abc'),你会得到一个Unicode字符串,上面写着b'abc',但它包含6个字符:b和引号在那里。这就是区别。您编写的文件是一个包含 Unicode 字符串的 Unicode 文件,该字符串以文字字符 "b'" 开头。

解决办法是用二进制模式打开你的文件:

import os
import hashlib

username = "coolcat"
password = "my secret password!!"

result = hashlib.sha1(password.encode("utf-8"))

with open(f"{username}.txt", "wb") as file:
   file.write(result.digest())

userinput = input("Your username please : ")
passwordinput = input("Your password please : ")
resulte = hashlib.sha1(passwordinput.encode("utf-8"))
print(resulte.digest())
try :
    with open(f"{userinput}.txt", "rb") as file:
        hashed = file.read()

    if hashed == resulte.digest():
        print("Access Granted")
    if hashed != resulte.digest():
        print("Wrong password!!")
except FileNotFoundError :
    print("Username not found!!1!")

【讨论】:

    【解决方案2】:

    假设您要比较两个字符串,也将散列输出更改为字符串。除了您将字节与字符串进行比较之外,该字符串将始终返回 false。

    import os
    import hashlib
    
    username = "coolcat"
    password = "my secret password!!"
    
    result = hashlib.sha1(password.encode("utf-8"))
    
    if not os.path.exists(f"{username}.txt"):
        open(f"{username}.txt", 'w').close()
    with open(f"{username}.txt", "w") as file:
       file.write(str(result.digest()))
    
    userinput = input("Your username please : ")
    passwordinput = input("Your password please : ")
    resulte = hashlib.sha1(passwordinput.encode("utf-8"))
    print(str(resulte.digest()))
    try :
        with open(f"{userinput}.txt", "r") as file:
            hashed = str(file.read())
        print(str(hashed))
    
        if hashed == str(resulte.digest()):
            print("Access Granted")
        if hashed != str(resulte.digest()):
            print("Wrong password!!")
    except FileNotFoundError :
        print("Username not found!!1!")
    

    【讨论】:

    • 但是....file.read() 已经返回了一个字符串...它是resulte.digest() 返回字节...
    • 同样,无需将hashed 转换为字符串。从一开始就已经是一个......
    • 我的意思是说两者都应该是字符串才能得到真实的。
    • 我同意。我只是说file.read() 已经返回一个字符串(在文本模式下打开时)所以不需要用str(...) 包装它
    猜你喜欢
    • 2017-04-08
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多