Python 2.7 Python 3 Unicode对象必须在散列之前进行编码
我将此代码用于哈希和salt:Python 2.7 Python 3 Unicode对象必须在散列之前进行编码,python-2.7,python-3.x,Python 2.7,Python 3.x,我将此代码用于哈希和salt: def make_hash(password): """Generate a random salt and return a new hash for the password.""" if isinstance(password, str): password = password.encode('utf-8') salt = b64encode(urandom(SALT_LENGTH)) print (salt, type(salt)) #print
def make_hash(password):
"""Generate a random salt and return a new hash for the password."""
if isinstance(password, str):
password = password.encode('utf-8')
salt = b64encode(urandom(SALT_LENGTH))
print (salt, type(salt))
#print (salt.encode('utf-8'), type(salt.encode('utf-8')))
return 'PBKDF2${}${}${}${}'.format(
HASH_FUNCTION,
COST_FACTOR,
salt,
b64encode(pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH,
getattr(hashlib, HASH_FUNCTION))))
以下是pbkdf2_箱:
def pbkdf2_bin(data, salt, iterations=1000, keylen=24, hashfunc=None):
"""Returns a binary digest for the PBKDF2 hash algorithm of `data`
with the given `salt`. It iterates `iterations` time and produces a
key of `keylen` bytes. By default SHA-1 is used as hash function,
a different hashlib `hashfunc` can be provided.
"""
hashfunc = hashfunc or hashlib.sha1
mac = hmac.new(data, None, hashfunc)
def _pseudorandom(x, mac=mac):
h = mac.copy()
h.update(x)
return map(int, h.digest())
buf = []
for block in range(1, -(-keylen // mac.digest_size) + 1):
rv = u = _pseudorandom(salt + _pack_int(block))
for i in range(iterations - 1):
u = _pseudorandom(''.join(map(chr, u)))
rv = starmap(xor, zip(rv, u))
buf.extend(rv)
return ''.join(map(chr, buf))[:keylen]
我已经调整了一些内容,如:
我替换了unicode->str
我替换了izip->zip
我更改了这个map(ord,h.digest())->map(int,h.digest())
对于Python2,它工作得很好。我刚刚跳进了python 3 我已经尝试了2个小时来解决这个问题,这里的所有解决方案都不适合我,可能我遗漏了什么。据我所知,我只需要添加
.encode(“utf-8”)
,但我已经尝试将其放在任何地方。我想它一定是salt
或者h.update(x)
中的x
我得到的Unicode对象在散列前必须进行编码,如下所示:
编辑
我找到了一行,如果我编码,会发生一些事情,但它会导致另一个错误
u = _pseudorandom(''.join(map(chr, u)).encode("utf-8"))
结果:
看看它是否有帮助?我看到了这个aleady,我也看到了每个类似的帖子,它对我不起作用。这正是我现在绊倒的地方。。。你同时解决了这个问题吗?@Nostrandamus是的,我解决了这个问题,我回家后会发布我的密码。@Roman:那太好了!同时,我通过使用另一个模块找到了解决方法。无论如何,出于好奇,我对这个解决方案很感兴趣。