来自 CryptoJS 和 Python Hashlib 的等效 MD5

Equivalent MD5 from CryptoJS and Python Hashlib

我尝试将一些代码从 JS 带到 Python。 我坚持使用 JS 中的代码:

const crypto = require('crypto')

var txtToHash = "Hello¤World¤";
var md5sum = crypto.createHash('md5');
md5sum.update(new Buffer(txtToHash, 'binary'));
md5val = md5sum.digest('hex');
// equivalent to
// crypto.createHash('md5').update(urlPart, 'binary').digest('hex'));

Returns : 3a091f847ee21c7c1927c19e0f29a28b

并且,在 Python 3.7 中,我有以下代码:

import hashlib

txtToHash = "Hello¤World¤"
md5val = hashlib.md5(txtToHash.encode()).hexdigest() 

Returns : f0aef2e2e25ddf71473aa148b191dd70

请问它们为什么不同?我在 Google 或 SO 上找不到答案。

您在摘要创建过程中使用了两种不同的字符编码。

确保您使用相同类型的字符编码。您的节点 js 实现使用 'binary' 别名 'latin1' 编码。 python 中的代码使用 UTf8 字符编码。

当您指定 txtToHash.encode() 时,这意味着将文本编码为 utf-8。

因此修改您的摘要创建以匹配两种环境中相同的字符编码。

要么修改你的nodejs代码

md5sum.update(new Buffer(txtToHash, 'utf8'));

或将您的 python 代码修改为

md5val = hashlib.md5(txtToHash.encode('latin1')).hexdigest()

以上应该给出相同的结果 >> 3a091f847ee21c7c1927c19e0f29a28b

注意: 虽然 python 代码给出了想要的结果。我不建议这样做,因为与 utf8 相比,latin1 编码只有一小部分字符。因此,我建议您在节点 js 应用程序中将编码更改为 utf-8,并在 python

中应用相同的编码