hashlib.md5().update('hi'):“TypeError: Unicode 对象必须在哈希之前进行编码”

问题描述 投票:0回答:8

我收到此错误:

>>> 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~'

Q1:

a
现在是否被认为是编码的?

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

import hashlib
a = hashlib.md5()
a.update('hi')
a.digest()
Traceback (most recent call last):
  File "C:/Users/User/Desktop/Logger/Encoding practice.py", line 3, in <module>
    a.update('hi')
TypeError: Unicode-objects must be encoded before hashing

Q2:为什么代码在 shell 中运行,而不是在脚本中运行?

我正在使用Python 3.4

python python-3.x encoding hash
8个回答
76
投票

我找到的解决方案是简单地在要散列数据的行中立即对数据进行编码:

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

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


26
投票

由于您正在编码简单的字符串,我推断您正在运行 Python 3,其中所有字符串都是 unicode 对象,因此您有两个选择:

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

    m.update(b"Nobody inspects")
    m.update(b" the spammish repetition")
    

脚本与 shell 中行为不同的原因是脚本在出现错误时停止,而在 shell 中,最后一行是一个单独的命令,但由于之前的错误,仍然没有执行您希望的操作。


5
投票

它在 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;'

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

print(a.hexdigest())

你在这里没有给出任何哈希值,因为在Python中一切都是unicode的,你必须首先将其编码为UTF-8(默认情况下)。


2
投票

不同版本的Python下是不一样的,我用的是Python 2.7,和你写的一样,运行良好。

hashlib.md5(data)函数,数据参数的类型应该是'bytes'。也就是说,我们必须把数据的类型放在哈希值之前。

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


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中注册的用户相同。


0
投票

适用于 py2/py3 的解决方案:

from six import ensure_binary
from hashlib import md5

md5(ensure_binary('hi')).digest()

0
投票

根据 Ignacio 的评论,这对我有用

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

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

© www.soinside.com 2019 - 2024. All rights reserved.