简体   繁体   中英

Same binary produces different md5

Check this out:

I want to encode a string as binary and print it's md5. I have 2 code bases: node and 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";

Produces this output:

/code # php md5.php 
18
171
53e035069bdb4f08a666fb7d42f29b15

Node:

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");

Produces this output:

/code # node md5.js
18
171
3f83d1a9a01e19e1a85665394f0f5a09

You can see the binary has the same code, and is in the same order. How is it possible to not have the same md5?

Don't store binary data in a string. It rarely works. Use the appropriate containers such as a Buffer :

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

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

The string should be switched to binary buffer before sending it to 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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM