Python 2 vs3。相同的输入,不同的结果。MD5哈希

Edu*_*o M 5 python md5 python-2.7 python-3.x

Python 3代码:

def md5hex(data):
    """ return hex string of md5 of the given string """
    h = MD5.new()
    h.update(data.encode('utf-8'))
    return b2a_hex(h.digest()).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

Python 2代码:

def md5hex(data):
    """ return hex string of md5 of the given string """
    h = MD5.new()
    h.update(data)
    return b2a_hex(h.digest())
Run Code Online (Sandbox Code Playgroud)

输入python 3:

>>> md5hex('bf5¤7¤8¤3')
'61d91bafe643c282bd7d7af7083c14d6'
Run Code Online (Sandbox Code Playgroud)

输入python 2:

>>> md5hex('bf5¤7¤8¤3')
'46440745dd89d0211de4a72c7cea3720'
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?

编辑:

def genurlkey(songid, md5origin, mediaver=4, fmt=1):
    """ Calculate the deezer download url given the songid, origin and media+format """
    data = b'\xa4'.join(_.encode("utf-8") for _ in [md5origin, str(fmt), str(songid), str(mediaver)])
    data = b'\xa4'.join([md5hex(data), data])+b'\xa4'
    if len(data)%16:
        data += b'\x00' * (16-len(data)%16)
    return hexaescrypt(data, "jo6aey6haid2Teih").decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

所有这些问题均始于另一个函数python 2代码中的b'\ xa4'。该字节在python 3中不起作用。

有了这个,我得到了正确的MD5哈希...

Tem*_*olf 5

使用hashlib和与语言无关的实现:

import hashlib
str = u'bf5¤7¤8¤3'
str = str.encode('utf-8')
print(hashlib.md5(str).hexdigest())
Run Code Online (Sandbox Code Playgroud)

在Python 2/3中工作,结果相同:

Python2:

'61d91bafe643c282bd7d7af7083c14d6'
Run Code Online (Sandbox Code Playgroud)

Python3(通过repl.it):

'61d91bafe643c282bd7d7af7083c14d6'
Run Code Online (Sandbox Code Playgroud)

您的代码失败的原因是编码后的字符串与编码后的字符串不同:您仅针对Python 3进行编码。


如果您需要它来匹配未编码的Python 2:

import hashlib
str = u'bf5¤7¤8¤3'
print(hashlib.md5(str.encode("latin1")).hexdigest())
Run Code Online (Sandbox Code Playgroud)

作品:

46440745dd89d0211de4a72c7cea3720
Run Code Online (Sandbox Code Playgroud)

Python 2的默认编码latin1不是utf-8