donglang2010
donglang2010
2017-06-17 08:07

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 dongtu1357 4年前

    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.

    点赞 评论 复制链接分享
  • dongpei2835 dongpei2835 4年前

    I am prefer use crypto-js library of crypto standards. This library is keep maintaining.

    const crypto = require('crypto-js')
    
    const public = 'JkAFq7M47kLN0xVD'
    const private = 'E6X9FyZvMFeJbqtq.IwjlTuR.MKDoicB'
    const url = 'https://pterodactyl.local/api/admin/users'
    const body = ''
    
    const hmac = crypto.HmacSHA256(url + body, private).toString(crypto.enc.Base64)
    
    console.log(public + '.' + hmac)
    // Print value:
    // JkAFq7M47kLN0xVD./RKZS3U2FKfEt7/tEks4vWwyS+89lL+k8aEGO8NJWuo=
    
    点赞 评论 复制链接分享

相关推荐