如何在 Python 2.6 的 MD5 散列中使用 bytearray?

How to use bytearray in MD5 hash in Python 2.6?

python 2.7 和 3.4 可以执行以下操作:

import hashlib
m = hashlib.md5()
m.update(bytearray(128))

但 python 2.6 生成错误消息:

    m.update(bytearray(128))
TypeError: update() argument 1 must be string or read-only buffer, not bytearray

如何在 Python 2.6 中解决这个问题?

在 Python 2.x 上,您可以简单地将字节数组转换为字符串,然后再将其传递给 update(),例如:

import hashlib
m = hashlib.md5()
m.update(str(bytearray(128)))

但是,这将在 Python 3.x 上产生错误的结果,因为 bytearray 不能直接转换为字符串。对于便携式版本,请使用以下代码,该代码在 Python 2.x 和 3.x 上工作相同:

import hashlib
m = hashlib.md5()
m.update(bytearray(128).decode('latin-1'))

请参阅 this answer 了解有关其工作原理的更多信息。