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

时间:2011-01-12 21:56:28

标签: python encoding character-encoding

在Python 3.1.1中的Ubuntu 10.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的打印看起来对我有用。

我真的很感激有关如何使其发挥作用的任何想法

1 个答案:

答案 0 :(得分:3)

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

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

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

为此,您可以使用:

authHash.hexdigest()

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

base64.b64encode(authHash.digest())
相关问题