【问题标题】:md5 cannot decode bytes [duplicate]md5无法解码字节[重复]
【发布时间】:2018-03-28 20:33:27
【问题描述】:

我正在尝试使用 hashlib 库调用 python3 中的服务。这段代码的最后一行抛出异常:

auth = hashed.digest().decode("utf-8").rstrip('\n')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 0: invalid start byte

这里是sn-p的代码:

import hashlib
m = hashlib.md5()
m.update("".encode("utf-8"))
data_hash = base64.b64encode(m.digest()).decode("utf-8")

# Create Authorization Header
canonical = '%s,application/vnd.api+json,%s,%s,%s' % (action, data_hash, url, format_date_time(stamp))
canonical = canonical.encode("utf-8")

hashed = hmac.new(bytearray(secret, "utf-8"), canonical, sha1)
auth = hashed.digest().decode("utf-8").rstrip('\n')

我错过了什么?

【问题讨论】:

  • 您希望摘要采用 UTF-8 编码吗?
  • ...或者换个说法,是什么让您期望摘要是 UTF-8 编码的?

标签: python python-3.x md5 url-encoding hashlib


【解决方案1】:

hashed.digest().decode("utf-8").rstrip('\n')

摘要返回字节,但没有任何字节序列是有效的 UTF-8。

我不知道您要完成什么,但这段代码有缺陷。

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 2016-11-03
    • 2016-07-10
    • 2017-09-02
    • 2013-12-19
    • 2016-05-09
    • 2023-03-28
    • 2016-12-16
    相关资源
    最近更新 更多