Skip to main content
 首页 » 编程设计

php之如果使用中文字符,为什么 php md5() 总是与 python 的 hash.md5() 不同

2025年05月04日17zhujiabin

这是我的 PHP 代码:

$str = '你好'; 
$input_encoding = mb_detect_encoding($str, array('ASCII','GB2312','GBK','UTF-8'), true); 
echo sprintf('input encoding:%s', $input_encoding); 
 
$str_gb = iconv($input_encoding, 'GBK', true); 
echo sprintf("utf8 encoding:%s\n", $str); 
echo sprintf("gb encoding md5:%s\n", md5($str_gb)); 
echo sprintf("utf8 encoding md5:%s\n", md5($str)); 

这是我的python代码:

#!/usr/bin/env python 
#coding:utf-8 
 
 
import urllib 
import hashlib 
 
str_u = u'你好' 
str_gb = str_u.encode('gbk') 
str_u8 = str_u.encode('utf-8') 
 
m = hashlib.md5() 
m.update(str_gb) 
str_gb_md5 = m.hexdigest() 
m.update(str_u8) 
str_u8_md5 = m.hexdigest() 
 
print 'gb md5:%s' % str_gb_md5 
print 'utf-8 md5:%s' % str_u8_md5 

PHP 代码结果是:

input encoding:CP936 
utf8 encoding:你好 
gb encoding md5:c4ca4238a0b923820dcc509a6f75849b 
utf8 encoding md5:7eca689f0d3389d9dea66ae112e5cfd7 

python 代码结果是:

gb md5:b94ae3c6d892b29cf48d9bea819b27b9 
utf-8 md5:a8a343223373c7d78c3fb8bad2d786c3 

这是我的编程环境: PHP 5.5.4 (cli)&Python 2.6.8

谢谢!

请您参考如下方法:

你的 php 和 python 代码都有错误。你php代码中的gbk md5和你python代码中的utf8 md5是错误的。

Python部分:

你误解了Python hashlib的hash.update函数的用法。

hash.update(arg)

Update the hash object with the string arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b).

修复:

print  hashlib.md5(str_u8).hexdigest() 
 
7eca689f0d3389d9dea66ae112e5cfd7 

PHP 部分:

您忘记将 $str 传递给 iconv 函数,而是传递了一个真值(隐藏为 1)。

修复:

$str = '你好'; 
$str_gb = iconv('UTF-8', 'GBK', $str); 
echo sprintf("gb encoding md5:%s\n", md5($str_gb)); 

输出:

gb编码md5:b94ae3c6d892b29cf48d9bea819b27b9

iconv definition :

string iconv ( string $in_charset , string $out_charset , string $str )