【问题标题】:Why do I need to declare encoding before hashing in Python, and how can I do this?为什么我需要在 Python 中散列之前声明编码,我该怎么做?
【发布时间】:2016-11-13 05:34:17
【问题描述】:

我正在尝试创建一个AI-like chatbot,它的功能之一是登录。我以前使用过登录代码,它工作正常,但我现在在处理密码散列的代码时遇到了困难。代码如下:

import hashlib
...
register = input ("Are you a new user? (y/n) >")

password_file = 'passwords.txt'
if register.lower() == "y": 
    newusername = input ("What do you want your username to be? >")
    newpassword = input ("What do you want your password to be? >")

    newpassword = hashlib.sha224(newpassword).hexdigest()

    file = open(password_file, "a")
    file.write("%s,%s\n" % (newusername, newpassword))
    file.close()

elif register.lower() == ("n"):
    username = input ("What is your username? >")
    password = input ("What is your password? >")

    password = hashlib.sha224(password).hexdigest()

    print ("Loading...")
    with open(password_file) as f:
        for line in f:
            real_username, real_password = line.strip('\n').split(',')
            if username == real_username and password == real_password:
                success = True
                print ("Login successful!")
              #Put stuff here! KKC
    if not success:
        print("Incorrect login details.")

这是我得到的结果:

Traceback (most recent call last):
  File "<FOLDERSYSTEM>/main.py", line 36, in <module>
    newpassword = hashlib.sha224(newpassword).hexdigest()
TypeError: Unicode-objects must be encoded before hashing

我查看了我认为应该使用的编码 (latin-1) 并找到了所需的语法,将其添加进去,我仍然收到相同的结果。

【问题讨论】:

    标签: python macos hash character-encoding password-storage


    【解决方案1】:

    散列适用于字节str 对象包含 Unicode 文本,而不是字节,因此您必须先进行编码。选择一种编码,a) 可以处理您可能遇到的所有代码点,并且可能 b) 产生相同哈希的其他系统也可以使用。

    如果您是哈希的唯一用户,则只需选择 UTF-8;它可以处理所有的 Unicode,对西方文本最有效:

    newpassword = hashlib.sha224(newpassword.encode('utf8')).hexdigest()
    

    hash.hexdigest() 的返回值是 Unicode str 值,因此您可以放心地将其与从文件中读取的 str 值进行比较。

    【讨论】:

    • 谢谢,但您所说的“唯一的哈希用户”是什么意思?这是一个 GitHub 项目,所以它仍然可以工作吗?另外,我已经尝试过了,注册很好,但是当我尝试登录时,它给了我:Traceback (most recent call last): File "/home/pi/Desktop/KittyKatCoder-edison-ai-3ae75b2/main.py", line 50, in &lt;module&gt; real_username, real_password = line.strip('\n').split(',') ValueError: need more than 1 value to unpack
    • @KittyKatCoder:假设您正在与另一个系统共享这些密码哈希;如果该系统使用 UTF-16 将 Unicode 文本编码为字节,那么您必须匹配该编码。不过,我敢打赌大多数系统都使用 UTF-8。
    • @KittyKatCoder:测试你的行中是否有逗号?您的文件末尾可能有一个空行; ''.split(',') 给你 一个 元素,而不是两个,所以你的分配失败。
    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2020-01-30
    相关资源
    最近更新 更多