douzhi1937 2019-08-13 10:45
浏览 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.

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

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路