【问题标题】:Python code for hashing byte values with md5使用 md5 散列字节值的 Python 代码
【发布时间】:2021-06-23 02:08:14
【问题描述】:

请接受一个尝试学习的缺乏经验(但非常热情)的程序员提出的这个问题:

我需要计算从 0x00 到 0xff 的每个字节组合的 md5 哈希值。我试图用 Python 来做这件事,但我不确定 Python 如何解释我的输入。如前所述,我需要散列字节值,而不是字符“fa”或“00”,而是值本身。

这是我测试过的一个代码示例。问题是 bytes.fromhex 的输出显示了一些表示为 ascii 的十六进制数字。我想那么 ascii 表示是散列的,而不是字节值。第二个问题是我不确定如何正确使用 hashlib 以便对字节值进行哈希处理。

导入哈希库

# Global variables


HEX_VALUES = {0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"a",11:"b",12:"c",13:"d",14:"e",15:"f"}


# Helper function for converting decimal number to another base.


def dec_to_base(num,base):

    exp = 0
    list1 = []
    while (num // base ** exp) > 0:
        num2 = (num // base ** exp) % base
        list1.insert(0,num2)
        exp += 1

    return list1

# Function for converting decimal to hex numbers.

def dec_to_hex(num):

    ret_val = []

    for x in dec_to_base(num,16):
        x = HEX_VALUES[x]
        ret_val.append(x)

    ret_val_str = ''.join(ret_val)
    ret_val_str_pad = ret_val_str.zfill(4)

    # Returns the hex number as a string with four zero-padding.

    return ret_val_str_pad


for i in range(1,65536):

    hex_number = bytes.fromhex(dec_to_hex(i))
    print(hex_number)

    h = hashlib.md5(hex_number)

    md5_hash = h.hexdigest()

    print(md5_hash)

    # Checks after TARGET STRING

【问题讨论】:

  • 1.) 字节输入,字节输出。 2.) 没有号码00,print(00) >> 0
  • 是的,所以在我的例子中,如果 00 产生的哈希值与 0 不同,程序必须将输入解释为字符串?
  • 没有。看代码。 hashlib.md5 的第一个参数是一个类似字节的对象。 “字符串”与字节不同。请参阅 strings 和 bytes-like 对象
  • 我已经更新了代码。随意看看。

标签: python hash byte md5 raw-data


【解决方案1】:

md5 接受字节但不接受字符串。

md5(b'00').hexdigest() # 'b4b147bc522828731f1a016bfa72c073'

md5('00').hexdigest() # TypeError: Unicode-objects must be encoded before hashing

字符串在传递给 md5 之前必须编码为字节。

md5('00'.encode()).hexdigest() # 'b4b147bc522828731f1a016bfa72c073'

'00'.encode() == b'00' # True
b'\x30\x30' == b'00' # True

在上述情况下,在 C 语言中,您将字节数组 {0x30, 0x30} 作为参数传递。在您的代码中,hex_number = bytes.fromhex(dec_to_hex(i)) 返回大小为 2 个字节。根据你的目标,你可能得不到你想要的。

hex_number = bytes.fromhex(dec_to_hex(1)) # b'\x00\x01'
md5(b'\x00\x01').hexdigest() # '441077cc9e57554dd476bdfb8b8b8102'
md5(b'\x01').hexdigest() # '55a54008ad1ba589aa210d2629c1df41'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2015-06-25
    • 1970-01-01
    • 2014-09-09
    相关资源
    最近更新 更多