donglang2010 2017-06-17 08:07
浏览 118
已采纳

NodeJS HMAC哈希创建

I am trying to follow part of a tutorial for an API written in PHP. They show the following example:

$public = 'JkAFq7M47kLN0xVD';
$private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';

$url = 'https://pterodactyl.local/api/admin/users';
$body = '';

$hmac = hash_hmac('sha256', $url . $body, $private, true);

return $public . '.' . base64_encode($hmac);

// Should return the string below:
//
// JkAFq7M47kLN0xVD.wgIxj+V8RHgIetcQg2lRM0PRSH/y5M21cPz9zVhfFaQ=

But my method doesn't return the proper value. Instead it returns the following:

JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=

Here is my code:

    hmac = crypto.createHmac('sha256', private_key);
    hmac.write(url+body);
    hmac.end();
    hash = hmac.read().toString('base64');
    console.log(hash);

EDIT: I think the example they provided was invalid because as everyone is saying my code is almost identical and the PHP code outputs a different value then it said it should in the documentation.

  • 写回答

2条回答 默认 最新

  • dongtu1357 2017-06-17 08:28
    关注

    ok so, i used this tool writephponline to run this php code:

    $public = 'JkAFq7M47kLN0xVD';
    $private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';
    
    $url = 'https://pterodactyl.local/api/admin/users';
    $body = '';
    
    $hmac = hash_hmac('sha256', $url . $body, $private, true);
    
    echo $public . '.' . base64_encode($hmac);
    

    and returns:

    JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
    

    So i used that as a parameter, then i made a little nodejs script:

    var crypto = require('crypto');
    
    var public = 'JkAFq7M47kLN0xVD';
    
    var private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB';
    
    var url = 'https://pterodactyl.local/api/admin/users';
    
    var body = '';
    
    var hmac = crypto.createHmac('sha256', private).update(url+body).digest('base64');
    
    console.log(public + '.' + hmac);
    

    and returns:

    JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
    

    Hope it helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建