以下 NodeJS MD5 哈希源代码的等效 PHP 版本是什么?



我正在从nodejs迁移到PHP,我无法为具有相同输入的以下代码片段获得类似的输出md5哈希摘要。也许我错过了什么。

var md5sum = crypto.createHash('md5');
md5sum.update(new Buffer(str, 'binary'));
md5_result = md5sum.digest('hex');

提前感谢您的帮助!!,顺便说一句,我的 nodejs 版本是 10.1.0,npm 版本是 5.6.0。对于那些询问的人,这个源代码等价物并不md5($str),也不是我的代码,我只是在转换它。例如,对于以下输入42b86318d761e13ef90c126c3e060582¤3¤724039¤1获得的摘要为9860bd2248c069c7b65045917c215596

我只是尝试在 https://www.tutorialspoint.com/execute_nodejs_online.php 运行以下代码片段,考虑到您的建议,但它们不起作用:

const crypto = require('crypto');
var str = "42b86318d761e13ef90c126c3e060582¤3¤724039¤1";
var md5sum = crypto.createHash('md5');
md5sum.update(new Buffer(str, 'binary'));
const md5_result = md5sum.digest('hex');
const md5 = crypto.createHash('md5').update(str).digest('hex');
const expected_digest = "9860bd2248c069c7b65045917c215596";
console.log("original version digest:" + md5_result);
console.log("proposed equivalent digest:" + md5);
console.log("expected digest:" + expected_digest);

我在那个网站上得到的是:original version digest:9860bd2248c069c7b65045917c215596 proposed equivalent digest:b8ee918f782fe7135b25c1fa59339094 expected digest:9860bd2248c069c7b65045917c215596

其他网站,如 https://www.katacoda.com/courses/nodejs/playground,https://repl.it/,https://www.jdoodle.com/execute-nodejs-online 支持我的说法(即md5摘要是9860bd2248c069c7b65045917c215596(,但是,到目前为止,这个网站 http://rextester.com/l/nodejs_online_compiler 输出你们中的一些人获得的东西(即b8ee918f782fe7135b25c1fa59339094(。正如我之前所说,请帮我找到第一个nodejs代码片段的PHP等效版本。

你不应该使用:new Buffer(str, 'binary')只是:

const md5 = crypto
.createHash('md5')
.update(string)
.digest('hex');

使用它,您将获得与phpmd5,linuxmd5sum和node相同的输出。

对于您的输入:42b86318d761e13ef90c126c3e060582¤3¤724039¤1以下命令将打印相同内容:

md5sum

echo -n "42b86318d761e13ef90c126c3e060582¤3¤724039¤1" | md5sum

.PHP

echo md5("42b86318d761e13ef90c126c3e060582¤3¤724039¤1");

节点

require('crypto')
.createHash('md5')
.update("42b86318d761e13ef90c126c3e060582¤3¤724039¤1")
.digest('hex');

所有三个都将输出:b8ee918f782fe7135b25c1fa59339094

注意:

new Buffer已弃用,则应改用Buffer.from

其他网站,如 https://www.katacoda.com/courses/nodejs/playground,https://repl.it/,https://www.jdoodle.com/execute-nodejs-online 支持我的主张(即 MD5摘要为9860BD2248C069C7B65045917C215596(

他们不支持您的主张,您正在许多不同的节点.js环境中执行相同的代码,这是错误的。当然,每个 Node.js 环境都会为您的代码打印该输出,这并不能使其正确。


由于您无法修改代码,并且您想要 PHP 等效项,因此这里是:

function utf8_char_code_at($str, $index) {
$char = mb_substr($str, $index, 1, 'UTF-8');
if (mb_check_encoding($char, 'UTF-8')) {
$ret = mb_convert_encoding($char, 'UTF-32BE', 'UTF-8');
return hexdec(bin2hex($ret));
} else {
return null;
}
}
function myMD5($str) {
$tmp = "";
for($i = 0; $i < mb_strlen($str); $i++)
$tmp .= bin2hex(chr(utf8_char_code_at($str, $i)));
return md5(hex2bin($tmp));
}
echo myMD5($string);

utf8_char_code_at取自:https://stackoverflow.com/a/18499265/1119863

它将输出:9860bd2248c069c7b65045917c215596与您的节点代码段相同。

最新更新