【发布时间】:2012-11-07 07:59:42
【问题描述】:
可能重复:
Python hashlib problem “TypeError: Unicode-objects must be encoded before hashing”
这是 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',它没有编码。
标签: python python-3.x