python - 将字节读入十六进制摘要字符串的方法

标签 python hash binaryfiles

我正在从名为 raw 的二进制缓冲区读取 16 个字节:

md5 = list(struct.unpack('16B', raw.read(16)))

这会产生以下列表:

>>> print(md5)
>>> [25, 94, 158, 89, 108, 25, 125, 20, 138, 164, 84, 137, 250, 82, 150, 202]

我需要构建一个正确的 md5 字符串,然后用它来与 hashlib.md5() 中的任何 hexdigest() 进行比较

目前我正在这样做:

md5 = list(struct.unpack('16B', raw.read(16)))
for i, b in enumerate(md5):
    md5[i] = hex(b)
md5 = ''.join(md5).replace('0x', '')

这可行,但我忍不住觉得我错过了一些东西。 缓冲区中的数据和最终字符串之间是否有更直接的转换

Note: I understand I have other types of digests. But currently I'm interested in solving the problem for an hexadecimal digest.

最佳答案

您可以使用 hexlifybytes (Python 3)/二进制 str (Python 2) 转换为十六进制字符串(字符串在 Python 3 上将是 bytes,因此我们需要 .decode('ascii') 来匹配作为 hexdigest str)。

from binascii import hexlify
hex_string = hexlify(raw.read(16)).decode('ascii')

if md5.hexdigest() == hex_string:
    ...

同样,您可以将原始字节与digest()进行比较; hexdigest() 只是 16 字节值的 32 个字符可读表示,该值是实际的 MD5 摘要和。

the_bytes = raw.read(16)
if md5.digest() == the_bytes:
    ...

关于python - 将字节读入十六进制摘要字符串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28768962/

相关文章:

python - 分辨率大于 1 秒的 signal.alarm 函数?

c++ - 如何在 Cython 中使用 C++ operator[]?

c - 如何在 C 代码中构建 Perl 哈希?

c++ - "Error reading character of string"为散列动态增长数组的问题 (C++)

python - __str__ 和 pretty-print (子)字典

python - 如何使用树莓派 PREEMPT_RT 补丁让进程实时运行?

java - 完善的哈希函数和好处

c - 我没有正确使用 fseek() 吗?

c++ - 使用/不使用 ios::binary 模式打开流时使用读/写的区别

c++ - reinterpret_cast 是如何工作的?