首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Hashlib unicode错误

Hashlib unicode错误
EN

Stack Overflow用户
提问于 2014-07-01 10:13:02
回答 1查看 427关注 0票数 0

我试图破解密码,但无法成功。这是密码。

代码语言:javascript
复制
from hashlib import sha1 as sha_constructor
import random


def generate_sha1(string, salt=None):
    if not isinstance(string, (str, str)):
        string = str(string)
    if isinstance(string, str):
        string = string.encode("utf-8")
    if not salt:
        salt = sha_constructor(str(random.random())).hexdigest()[:5]
    hash = sha_constructor(salt + string).hexdigest()

    return salt, hash


a = generate_sha1('12345')
print(a)

我得到了这个错误。

代码语言:javascript
复制
TypeError: Unicode-objects must be encoded before hashing

我做错什么了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-01 10:15:11

对于Python 2,请尝试

代码语言:javascript
复制
if isinstance(string, unicode):

而不是

代码语言:javascript
复制
if isinstance(string, str):

而且,isinstance(string, (str, str)):也没有意义。应该是isinstance(string, (str, unicode)):

编辑 For Python3,您需要将参数编码为sha_constructor()

代码语言:javascript
复制
arg = str(random.random()).encode('utf-8')
salt = sha_constructor(arg).hexdigest()[:5]

如果使用+运算符,Python将再次创建一个必须编码的(unicode)字符串。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24507691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档