[英]Same binary produces different md5
看一下這個:
我想將字符串編碼為二進制並將其打印為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?
不要將二進制數據存儲在字符串中。 它很少起作用。 使用適當的容器,例如Buffer
:
const crypto = require("crypto");
const key = "12ab";
console.log(crypto.createHash('md5').update(new Buffer(key, "hex")).digest("hex"));
在將字符串發送到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"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.