【问题标题】:Python 3.3 - Unicode-objects must be encoded before hashing [duplicate]Python 3.3 - 必须在散列之前对 Unicode 对象进行编码 [重复]
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 不工作。哪个是正确的:return hashlib.sha256(pw.encode('utf-8') + salt.encode('utf-8')).hexdigest()+","+ saltreturn hashlib.sha256((pw + salt).encode('utf-8').hexdigest()+","+ salt
  • @Grienders 我会尽早使用字节。因此,单独对 pw 进行编码(或首先将其视为字节,b'123')并已经将哈希创建为字节。所以在make_pw_hash() 中使用string.ascii_letters.encode("latin1")(或utf8,结果相同)。这不会改变算法,只会改变实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-12
  • 1970-01-01
  • 2020-03-25
  • 1970-01-01
  • 2016-01-15
  • 1970-01-01
相关资源
最近更新 更多