用MD5()在Python中编译码

2024-04-26 10:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3.1.1中的Ubuntu10.10上运行此代码

我得到以下错误:

UnicodeDecodeError:“utf8”编解码器无法解码位置0中的字节0xd3:无效的连续字节

错误的位置会根据运行以下代码的时间而变化: (不是真正的钥匙或秘密)

sandboxAPIKey = "wed23hf5yxkbmvr9jsw323lkv5g"
sandboxSharedSecret = "98HsIjh39z"

def buildAuthParams():
    authHash = hashlib.md5();

    #encoding because the update on md5() needs a binary rep of the string
    temp = str.encode(sandboxAPIKey + sandboxSharedSecret + repr(int(time.time())))
    print(temp)

    authHash.update(temp)

    #look at the string representation of the binary digest
    print(authHash.digest())

    #now I want to look at the string representation of the digest
    print(bytes.decode(authHash.digest()))

这是运行的输出(sig和密钥信息从实际输出更改)

b'sdwe5yxkwewvr9j343434385gkbH4343h4343dz129443643474'
b'\x945EM3\xf5\xa6\xf6\x92\xd1\r\xa5K\xa3IO'

print(bytes.decode(authHash.digest()))
UnicodeDecodeError: 'utf8' codec can't decode byte 0x94 in position 0: invalid start byte

我想我的电话解码有问题,但我不知道是什么。authHash.digest的打印对我来说是有效的。

我真的很感激你能想出什么办法


Tags: ofthe代码string字节错误utf8解码
1条回答
网友
1楼 · 发布于 2024-04-26 10:18:49

当您尝试将bytearray解码为字符串时,它会尝试按顺序将字节与编码集的有效字符(默认情况下为utf-8)匹配,这会引发异常,因为它无法将字节序列与utf-8字母表中的有效字符匹配。

如果尝试使用ascii解码,则会发生同样的情况,任何大于127的值都是无效的ascii字符。

因此,如果您试图获得md5哈希的可打印版本,应该对其进行十六进制摘要,这是打印任何类型哈希的标准方法,每个字节都由两个十六进制数字表示。

为此,您可以使用:

authHash.hexdigest()

如果需要在url中使用它,可能需要将bytearray编码为base64:

base64.b64encode(authHash.digest())

相关问题 更多 >