Python 和 PHP 之间的 MD5 不匹配

MD5 Mismatch between Python and PHP

我正在尝试比较 PHP 和 Python 之间的 MD5 字符串,我们的服务器在 PHP 客户端上工作正常,但是当我们尝试在python,我们总是从服务器收到无效响应。

我有以下代码 Python

import hashlib
keyString = '96f6e3a1c4748b81e41ac58dcf6ecfa0'
decodeString = ''
length = len(keyString)
for i in range(0, length, 2):
   subString1 = keyString[i:(i + 2)]
   decodeString += chr(int(subString1, 16))
print(hashlib.md5(decodeString.encode("utf-8")).hexdigest())

Produces: 5a9536a1490714cb77a02080f902be4c

现在,PHP中的相同概念:

$serverRandom = "96f6e3a1c4748b81e41ac58dcf6ecfa0";
$length = strlen($serverRandom);
$server_rand_code = '';
for($i = 0; $i < $length; $i += 2)
  {
    $server_rand_code .= chr(hexdec(substr($serverRandom, $i, 2)));
  }
echo 'SERVER CODE: '.md5($server_rand_code).'<br/>';

Produces: b761f889707191e6b96954c0da4800ee

我尝试检查编码,但没有成功,两个 MD5 输出根本不匹配,有帮助吗?

看来你生成字节串的方法不对,所以hashlib.md5的输入是错误的:

print(decodeString.encode('utf-8'))
# b'\xc2\x96\xc3\xb6\xc3\xa3\xc2\xa1\xc3\x84t\xc2\x8b\xc2\x81\xc3\xa4\x1a\xc3\x85\xc2\x8d\xc3\x8fn\xc3\x8f\xc2\xa0'

将字符串解释为十六进制字节字符串的最简单方法是使用 binascii.unhexlify, or bytes.fromhex:

import binascii

decodeString  = binascii.unhexlify(keyString)
decodeString2 = bytes.fromhex(keyString)

print(decodeString)
# b'\x96\xf6\xe3\xa1\xc4t\x8b\x81\xe4\x1a\xc5\x8d\xcfn\xcf\xa0'

print(decodeString == decodeString2)
# True

您现在可以直接在 hashlib.md5 中使用生成的 bytes 对象:

import hashlib

result = hashlib.md5(decodeString)
print(result.hexdigest())
# 'b761f889707191e6b96954c0da4800ee'