hashlib.md5()TypeError:必须在散列之前对Unicode对象进行编码

时间:2014-12-17 06:06:51

标签: python python-3.x encoding hash

我是编码的新手,并且在尝试编码字符串时遇到了问题。

>>> import hashlib
>>> a = hashlib.md5()
>>> a.update('hi')
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    a.update('hi')
TypeError: Unicode-objects must be encoded before hashing
>>> a.digest()
b'\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\t\x98\xec\xf8B~'

现在(a)是否被编码?

第二个问题:当我在脚本中运行上面相同的代码时,我收到此错误:

import hashlib
a = hashlib.md5()
a.update('hi')
a.digest()

追踪(最近一次通话):   文件&#34; C:/ Users / User / Desktop / Logger / Encoding practice.py&#34;,第3行,in     a.update(&#39;喜&#39;) TypeError:必须在散列之前对Unicode对象进行编码

为什么代码在shell中工作而不是脚本? 我正在使用Windows和Python 3.4

感谢。

8 个答案:

答案 0 :(得分:19)

由于您编写简单的字符串,我推断您运行的是Python 3,其中所有字符串都是unicode对象,您有两种选择:

  1. 为字符串提供编码,例如:"Nobody inspects".encode('utf-8')
  2. 使用二进制字符串,如手册中所示:

    m.update(b"Nobody inspects")
    m.update(b" the spammish repetition")
    
  3. 脚本中与shell的行为不同的原因是脚本在错误上停止,而在shell中,最后一行是一个单独的命令,但由于先前的错误,仍然没有按照您的意愿执行操作。 / p>

答案 1 :(得分:15)

我发现的解决方案是简单地将数据编码在你要对其进行散列的行中:

hashlib.sha256("a".encode('utf-8')).hexdigest()

它对我有用,希望它有所帮助!

答案 2 :(得分:2)

在不同版本的Python下不同,我使用的是Python 2.7,和你写的一样,效果很好。

hashlib.md5(数据)函数,数据参数的类型应该是'bytes'。也就是说,我们必须在散列之前将数据类型放入字节中。

哈希码转换前的要求,因为相同的字符串在不同的编码系统下具有不同的值(utf8 \ gbk .....),为了确保不发生歧义,必须进行显性转换。

答案 3 :(得分:1)

它没有在REPL中工作。它没有任何哈希值,因为你已经通过它没有任何有效的哈希值。首先尝试编码。

3>> hashlib.md5().digest()
b'\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\t\x98\xec\xf8B~'
3>> a = hashlib.md5()
3>> a.update('hi'.encode('utf-8'))
3>> a.digest()
b'I\xf6\x8a\\\x84\x93\xec,\x0b\xf4\x89\x82\x1c!\xfc;'

答案 4 :(得分:1)

对于Python3,以下方法有效。

secretKey = b"secret key that you get from Coginito -> User Pool -> General Settings -> App Clients-->Click on Show more details -> App client secret"
        clientId = "Coginito -> User Pool -> General Settings -> App Clients-->App client id"
        digest = hmac.new(secretKey,
                  msg=(user_name + clientId).encode('utf-8'),
                  digestmod=hashlib.sha256
                 ).digest()
        signature = base64.b64encode(digest).decode()

上面的用户名user_name与您要在cognito中注册的用户相同。

答案 5 :(得分:0)

在py2 / py3中都可以使用的解决方案:

[https://jsfiddle.net/r0bin/0m13h5fk/1/][1]

答案 6 :(得分:0)

a = hashlib.md5(("the thing you want to hash").encode())

print(a.hexdigest())

您在这里不做任何散列,因为在python中所有内容都是unicode,因此您必须先将其编码为UTF-8(默认情况下)。

答案 7 :(得分:-1)

这对我有用,基于 Ignacio 评论

xx = "RT6SJ65UW56"+var+"fgfgfng" ##任意一组字符串

yy = hashlib.md5(xx.encode('UTF-8')).hexdigest()