为什么我需要在Python散列之前声明编码,我该如何做?

为什么我需要在Python散列之前声明编码,我该如何做?,python,macos,hash,character-encoding,password-storage,Python,Macos,Hash,Character Encoding,Password Storage,我正在尝试创建一个,它的一个特性是登录。我以前使用过登录代码,它工作得很好,但现在我在处理密码散列的代码时遇到了困难。代码如下: 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 user

我正在尝试创建一个,它的一个特性是登录。我以前使用过登录代码,它工作得很好,但现在我在处理密码散列的代码时遇到了困难。代码如下:

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
回溯(最近一次呼叫最后一次):
文件“/main.py”,第36行,在
newpassword=hashlib.sha224(newpassword).hexdigest()
TypeError:在散列之前必须对Unicode对象进行编码
我已经查找了我认为应该使用的编码(latin-1),找到了所需的语法,并在中添加了该语法,我仍然收到了相同的结果。

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

如果您是散列的唯一用户,那么只需选择UTF-8;它可以处理所有Unicode,对于西方文本来说效率最高:

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

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

谢谢,但您所说的“哈希的唯一用户”是什么意思?这是一个GitHub项目,那么它是否仍然适用于该项目?此外,我已经尝试过了,注册也没问题,但当我尝试登录时,它会给我:
回溯(最近的一次调用):文件“/home/pi/Desktop/KittyKatCoder-edison-ai-3ae75b2/main.py”,第50行,真实用户名,真实密码=line.strip('\n')。拆分(','))ValueError:需要超过1个值才能解包
@KittyKatCoder:假设您正在与其他系统共享这些密码哈希;如果该系统使用UTF-16将Unicode文本编码为字节,则必须匹配该编码。但我敢打赌大多数系统都使用UTF-8。@KittyKatCoder:测试你的行中是否有逗号?您的文件末尾可能有一个空行<代码>''。拆分(',')为您提供一个元素,而不是两个元素,因此分配失败。