Python 3.3 - 必须在散列之前对Unicode对象进行编码

24 python python-3.x

可能重复:
Python hashlib问题"TypeError:必须在散列之前编码Unicode对象"

这是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)
Run Code Online (Sandbox Code Playgroud)

它给我的错误是:

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
Run Code Online (Sandbox Code Playgroud)

我不允许更改生成密码的算法,所以我只想使用可能的方法修复错误encode('utf-8').我该怎么做?

Thi*_*ter 33

只需调用你在pwsalt字符串上提到的方法:

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