可能重复:
Python hashlib problem “TypeError: Unicode-objects must be encoded before hashing”的Python 3.3 - Unicode的对象必须散列之前被编码
这里是在Python 3的码,其与盐生成密码:
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
我不允许更改生成密码的算法,所以我只想用方法encode('utf-8')
修复错误。我该怎么做?
问题是与''123'',它没有编码。 –