在Python中使用MD5进行编码和解码

3 投票
1 回答
9659 浏览
提问于 2025-04-16 09:52

在Ubuntu 10.10上运行这个代码,使用的是Python 3.1.1。

我遇到了以下错误:

UnicodeDecodeError: 'utf8' 编码无法解码字节 0xd3 在位置 0: 无效的继续字节

而且这个错误的位置会根据我运行以下代码的时机而变化:

(这些不是实际的密钥或秘密)

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

这是运行后的输出(签名和密钥信息已从真实输出中更改)

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的打印结果在我看来是有效的。

我非常希望能得到一些建议,看看怎么才能让这个代码正常工作。

1 个回答

4

当你试图把一个字节数组解码成字符串时,它会逐个比对字节,看看能不能找到对应的有效字符(默认情况下是用utf-8编码)。如果找不到匹配的字符,就会出现错误。

如果你用ascii来解码,也是一样的道理,任何大于127的值在ascii中都是无效字符。

所以,如果你想要得到md5哈希的可打印版本,你应该使用hexdigest,这是一种标准的打印哈希的方法,每个字节用两个十六进制数字表示。

要做到这一点,你可以使用:

authHash.hexdigest()

如果你需要在网址中使用它,可能需要把字节数组编码成base64格式:

base64.b64encode(authHash.digest())

撰写回答