dongshilve4392 2017-03-28 07:29
浏览 109

nodejs和php生成的不同HMAC

// base64-encode the binary result of the HMAC computation
$merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true));

The above is the php code that generates the digest.

let h = crypto.createHmac('sha256', hmacKey).update(keyString).digest('base64');

The above is the nodejs code that generates the digest. The key that I am using is hexadecimal in both php and node. What should I be doing differently in node to get the same result as that in php. I know php uses a different encoding than nodejs. But, what else am I missing here?

  • 写回答

1条回答 默认 最新

  • dongyi5425 2017-03-28 08:17
    关注

    well, there are no difference between the hmac's in both php and node.js .

    this is the normal behavior for the two pieces of codes your provided.

    in your php you are packing your $hmacKey

    the step which is not exists in your node side;


    in all the next examples i will use 123456 as hmac key and yello as a data string

    for example :

    php without packing :

    $merchantSig = base64_encode(hash_hmac('sha256',$signData, $hmacKey,true));
    echo $merchantSig; // output : gKjrFq1nrRP33vGiAK9V1Z5bLX5EFZhcfy2flRIGPEI=
    

    node.js without packing :

    let h = crypto.createHmac('sha256', hmacKey).update(keyString).digest('base64');
    console.log(h); // output : gKjrFq1nrRP33vGiAK9V1Z5bLX5EFZhcfy2flRIGPEI=
    

    now let's pack the both :

    php with packing :

    $merchantSig = base64_encode(hash_hmac('sha256',$signData,pack("H*" , $hmacKey),true));
    echo $merchantSig; // output : Y8D5crzxQfFkwQn1OJHeZTS1KVuTH0y7qLuxyetE0TY=
    

    node.js with packing here is the trick

    var h = crypto.createHmac('sha256', hmacKey.packHex()).update(keyString).digest('base64');
    //                                          ^^^^^^^^^
    console.log(h); // output : Y8D5crzxQfFkwQn1OJHeZTS1KVuTH0y7qLuxyetE0TY=
    

    Update

    Here is some online tests for both php & nodejs in the two cases (using pack-without using pack)

    php : https://3v4l.org/HCt4g

    nodejs : http://rextester.com/YNNWN69327

    here is another tests with another keys and strings . for php :

    https://3v4l.org/JKdNk

    and node.js

    http://rextester.com/RXGM49887 ,

    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试