为什么我需要在Python中进行散列之前声明编码,我该怎么做呢?

时间:2016-07-11 09:59:54

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

我正在尝试创建AI-like chatbot,其中一项功能是登录。我之前使用过登录代码并且工作正常,但我现在遇到了处理密码散列的代码的困难。这是代码:

def reset_filter
    xvaziris = Xvaziri.all // or do the search here, depending on what you need
    xvaziris.each do |xvaziri|
        xvaziri.hidden = false
    end
    redirect_to xvaziris_url
end

以下是我得到的结果:

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.")

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

1 个答案:

答案 0 :(得分:1)

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

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

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

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