dongze5043 2016-03-16 14:02
浏览 1950
已采纳

NodeJS crypto.createHmac SHA256无法正常工作

I'm currently trying to implement the authentication part of a library we're using but I've stumbled upon a weird issue with the signing of the data, the output of crypto.createHmac in NodeJS is roughly half the size of that of hash_hmac in PHP and this is the only part of the data which differs between PHP and NodeJS (and we need to use NodeJS here)

The exact code used for creating the signature in NodeJS is,

authorization["oauth_signature"] = crypto.createHmac('SHA256', process.env.SECRET).update(toSign).digest('base64');

And for PHP it is

$authorization["oauth_signature"] = base64_encode(hash_hmac("SHA256", $signatureString . $signingKey, $secret));

However the output of the NodeJS version is

7LkQP+qKR1gSdPq/AgH/3No3ps7EtZXnqwjivMixvM8=

And for PHP it is

NmQ0MWIzYmJiMjI2YzFlMDhiYzY3NzVmMWY0MzEwNDlhNDU3NDI0ZGJlMzU3NjJhYmMwYjgwYzZjMDE4NDM4OA==

Which has more then double the data

Do I have to use a different library for the NodeJS version rather then the build in one? We're hosting our NodeJS backend on Microsoft Azure btw, not sure if this is related but seems at least valid to mention.

Edit:

I've found the issue, hash_hmac in PHP automatically exports it's data as hexidecimal data, crypto.createHmac exports it's data as raw binary data which I directly converted into base64, all I needed to do was first export the data to hex and then convert that to base64.

  • 写回答

2条回答 默认 最新

  • doulangdang9986 2016-03-16 14:20
    关注

    Try this;

    var crypto = require('crypto');
    var s = 'The quick brown fox jumps over the lazy dog';
    console.log(
        new Buffer(
            crypto.createHmac('SHA256', 'SECRET').update(s).digest('hex')
        ).toString('base64')
    );
    

    DEMO

    PHP equivalent;

    base64_encode(hash_hmac("SHA256",'The quick brown fox jumps over the lazy dog', 'SECRET'))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵