简体   繁体   English

Python和PHP之间的MD5不匹配

[英]MD5 Mismatch between Python and PHP

I am trying to compare the MD5 string between PHP and Python, the server we have is working fine with PHP clients, but when we tried to do the same in python, we always get an invalid response from the server.我正在尝试比较 PHP 和 Python 之间的 MD5 字符串,我们拥有的服务器在 PHP 客户端上运行良好,但是当我们尝试在 python 中执行相同操作时,我们总是从服务器收到无效响应。

I have the following piece of code In 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

now, the same concept in PHP:现在,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

I tried checking the encoding, but no luck, the two MD5 output don't match at all, any help?我尝试检查编码,但没有运气,两个 MD5 output 根本不匹配,有帮助吗?

Looks like your method of generating the byte string is incorrect, so the input to hashlib.md5 is wrong:看起来你生成字节串的方法不正确,所以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'

The easiest way to interpret the string as a hex string of bytes is to use binascii.unhexlify , or bytes.fromhex :将字符串解释为十六进制字节字符串的最简单方法是使用binascii.unhexlifybytes.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

You can now directly use the resulting bytes object in hashlib.md5 :您现在可以直接在 hashlib.md5 中使用生成的bytes hashlib.md5

import hashlib

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM