python - 为什么在 Python 中需要在哈希之前声明编码,以及如何执行此操作?

标签 python macos hash character-encoding password-storage

我正在尝试创建一个 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)并找到了所需的语法,将其添加到其中,我仍然收到相同的结果。

最佳答案

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

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

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

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

关于python - 为什么在 Python 中需要在哈希之前声明编码,以及如何执行此操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38304088/

相关文章:

ctime 返回 null

java - JDK 中可用的 MessageDigest 的完整列表

arrays - 在 Perl 中的哈希中遍历哈希数组

Python 错误 - ImportError : No module named _weakrefset

objective-c - 10.10 中 NSTableView 的 selectRowIndexes 或 scrollRowToVisible 崩溃

python - rdflib "repeat node-elements"OWL/XML 文件解析错误

macos - 权限错误通过 osx 上的 vagrant 通过 Chef 通过 Homebrew 软件安装 ruby

php - 向哈希添加盐后无法使登录脚本工作;之前工作得很好

python - Python 3 中的 FastCGI WSGI 库?

python - 为什么在 Windows 上使用 cmd 的 Python 会忽略 %PYTHONPATH%?