douzhi1937 2019-08-13 10:45 采纳率: 0%
浏览 295
已采纳

如何在nodejs中实现“gzencode”(PHP函数)

I have some API which need the sign with encrypted by gzencode function in php, now I need to use nodejs to make a test tools for testing these API.

I've tried pako and zlib module in nodejs, however, the compress result was always different from php, so I want to know how can I make the same compress result in nodejs like gzencode in php7 ?

const pako = require('pako');
const zlib = require('zlib');
const crypto = require('crypto');

const input = '1234';

zlib.gzip(input, (err, buffer) => {
    if (!err) {
        console.log("--------zlib result---------");
        console.log(buffer.toString());
        console.log("");
        console.log("length: " + buffer.toString().length);
        console.log("md5: " + crypto.createHash('md5').update(buffer.toString()).digest("hex"));
    }
});

var result = pako.gzip(input, { to: 'string' });
console.log("--------pako result---------");
console.log(result);
console.log("");
console.log("length: " + result.length);
console.log("md5: " + crypto.createHash('md5').update(result).digest("hex"));
$str = gzencode('1234');
var_dump($str);
var_dump(strlen($str));
var_dump(md5($str));

nodejs result

pako result

3426 £àã
length: 24
md5: 45461056d1301798aae739d467b1811b

zlib result

3426 ���
length: 23
md5: ea90ab1d16e5596020fb313119879e26<br/>

php result

string(24) "3426"
int(24)
string(32) "cbe26958c184e607833efbf9b63516fb"
  • 写回答

1条回答 默认 最新

  • dongyou26216708 2019-08-16 11:12
    关注

    This is a slightly tricky one to diagnose, but in the end the fix is, thankfully, quite small:

    Instead of:

    crypto.createHash('md5').update(buffer.toString()).digest("hex"));
    

    we'll just update with the buffer object itself:

    crypto.createHash('md5').update(buffer).digest("hex"));
    

    So the updated code is:

    const zlib = require('zlib');
    const crypto = require('crypto');
    
    const input = '1234';
    
    zlib.gzip(input, (err, buffer) => {
        if (!err) {
            console.log("--------Zlib result---------");
            console.log("buffer (hex): ", buffer.toString("hex"));
            console.log("");
            console.log("length: " + buffer.length);
            console.log("md5: " + crypto.createHash('md5').update(buffer).digest("hex"));
        }
    });
    

    Now both the Node.js and PHP code produce an md5 output of:

    cbe26958c184e607833efbf9b63516fb
    

    For the input ('1234').

    As you noted above, this may be platform dependent.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?