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

标签 php python hash md5

这是我的 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 )

关于php - 如果使用中文字符,为什么 php md5() 总是与 python 的 hash.md5() 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19782510/

相关文章:

php - 每小时删除旧的 MySQL 记录

php - 获取 WooCommerce 可变产品单页中选定的产品变体 ID

file - 文件 MD5 Hash 代表什么?

c# - SHA512 托管哈希大小

php - 如果 foreach 中存在行则不起作用

php - 验证数据,登录系统codeigniter

python - Tkinter 常规语句不起作用

python - 如何使用 python 打开 gnome-terminal 然后以多行方式运行 python 命令?

python - 需要正则表达式才能在 python 中仅获取 Tably 名称和主键

hash - PGP要散列的数据长度