gpt4 book ai didi

python - 使用 MD5( ) 在 Python 中编码和解码

转载 作者:太空宇宙 更新时间:2023-11-04 01:41:11 25 4
gpt4 key购买 nike

在 Python 3.1.1 中的 Ubuntu 10.10 上运行这段代码

我收到以下错误:

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

并且错误的位置会根据我运行以下代码的时间而变化:(不是真正的 key 或 secret )

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()))

这是运行的输出(签名和 key 信息与实际输出不同)

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 的输出对我来说似乎有效。

如果有任何关于如何让它工作的想法,我将不胜感激

最佳答案

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

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

因此,如果您想要获得 md5 散列的可打印版本,您应该对其进行 hexdigest,这是打印任何类型散列的标准方法,每个字节由 2 个十六进制数字表示。

为此,您可以使用:

authHash.hexdigest()

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

base64.b64encode(authHash.digest())

关于python - 使用 MD5( ) 在 Python 中编码和解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4674465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com