【问题标题】:Same binary produces different md5相同的二进制文件产生不同的 md5
【发布时间】:2016-09-21 07:29:24
【问题描述】:

看看这个:

我想将字符串编码为二进制并将其打印为 md5。我有 2 个代码库:node 和 php。

PHP:

<?php
$key="12ab";
$hex_key = pack('H*', $key);
for ($i=0; $i<strlen($hex_key); $i++) {
    echo ord(substr($hex_key, $i ,1))."\n";
}       
echo md5($hex_key)."\n";

产生这个输出:

/code # php md5.php 
18
171
53e035069bdb4f08a666fb7d42f29b15

节点:

const crypto = require("crypto");
const key = "12ab";

let hex_key = "";

for (let i = 0; i < key.length; i += 2) {
    hex_key += String.fromCharCode( parseInt(key[i] + key[i+1], 16) );
}
for (var i = 0; i < hex_key.length; i++) {
    console.log(hex_key.charCodeAt(i));        
}
console.log( crypto.createHash('md5').update( hex_key).digest("hex");

产生这个输出:

/code # node md5.js
18
171
3f83d1a9a01e19e1a85665394f0f5a09

您可以看到二进制文件具有相同的代码,并且顺序相同。 怎么可能没有相同的md5?

【问题讨论】:

  • 有以下两种可能性之一: 1. MD5 在其中一种实现中被破坏。 2.您没有提供相同的输入。我会打赌 #2,调试并确保以预期格式提供值并且正确显示输出。

标签: php node.js character-encoding cryptography md5


【解决方案1】:

不要将二进制数据存储在字符串中。它很少起作用。使用适当的容器,例如Buffer:

const crypto = require("crypto");
const key = "12ab";

console.log(crypto.createHash('md5').update(new Buffer(key, "hex")).digest("hex"));

【讨论】:

    【解决方案2】:

    字符串在发送到 md5 之前应该切换到二进制缓冲区

    const crypto = require("crypto");
    const key = "12ab";
    
    let hex_key = "";
    
    for (let i = 0; i < key.length; i += 2) {
        hex_key += String.fromCharCode( parseInt(key[i] + key[i+1], 16) );
    }
    var str = ""
    console.log('length ' + hex_key.length);
    for (var i = 0; i < hex_key.length; i++) {
        console.log(hex_key.charCodeAt(i));
    }
    console.log( crypto.createHash('md5').update(new Buffer(hex_key, "binary")).digest("hex"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多