Python3.3-在散列之前必须对Unicode对象进行编码

Python3.3-在散列之前必须对Unicode对象进行编码,python,python-3.x,Python,Python 3.x,可能重复: 下面是Python 3中的一段代码,该代码生成了一个带salt的密码: import hmac import random import string import hashlib def make_salt(): salt = "" for i in range(5): salt = salt + random.choice(string.ascii_letters) return salt def make_pw_hash(pw,

可能重复:

下面是Python 3中的一段代码,该代码生成了一个带salt的密码:

import hmac
import random
import string
import hashlib


def make_salt():
    salt = ""
    for i in range(5):
        salt = salt + random.choice(string.ascii_letters)
    return salt


def make_pw_hash(pw, salt = None):
    if (salt == None):
        salt = make_salt() #.encode('utf-8') - not working either
    return hashlib.sha256(pw + salt).hexdigest()+","+ salt


pw = make_pw_hash('123')
print(pw)
它给我的错误是:

Traceback (most recent call last):
  File "C:\Users\german\test.py", line 20, in <module>
    pw = make_pw_hash('123')
  File "C:\Users\german\test.py", line 17, in make_pw_hash
    return hashlib.sha256(pw + salt).hexdigest()+","+ salt
TypeError: Unicode-objects must be encoded before hashing
回溯(最近一次呼叫最后一次):
文件“C:\Users\german\test.py”,第20行,在
pw=make_pw_散列('123'))
文件“C:\Users\derman\test.py”,第17行,make\u pw\u散列
返回hashlib.sha256(pw+salt).hexdigest()+“,”+salt
TypeError:在散列之前必须对Unicode对象进行编码

我不允许更改生成密码的算法,因此我只想使用
encode('utf-8')
方法修复错误。我怎么做?

只需调用您在
pw
salt
字符串中提到的方法:

pw_bytes = pw.encode('utf-8')
salt_bytes = salt.encode('utf-8')
return hashlib.sha256(pw_bytes + salt_bytes).hexdigest() + "," + salt

问题在于
'123'
,它没有编码。无法工作。哪一个是正确的:
返回hashlib.sha256(pw.encode('utf-8')+salt.encode('utf-8')).hexdigest()+”、“+salt
返回hashlib.sha256((pw+salt).encode('utf-8').hexdigest()+”、“+salt
@Grienders我会尽可能早地使用字节。所以分开对pw进行编码(或者首先将其预期为字节,
b'123'
)并已将哈希创建为字节。因此,在
make\u pw\u hash()
中使用
string.ascii\u letters.encode(“拉丁1”)
(或具有相同结果的utf8)。这不会改变算法,只会改变实现。