Equivalent to Hash_hmac in Node.js

I have code that works in my PHP application. In PHP, I sign a URL with the following code:

private static function __getHash($string)
{
    return hash_hmac('sha1', $string, self::$__secretKey, true);    
}

I am trying to sign the url in the same way in a Node.js application. This is what I am trying:

S3.prototype.getHash = function(string){
    var key = this.secret_key; 
    var hmac = crypto.createHash('sha1', key);
    hmac.update(string); 
    return hmac.digest('binary'); 
}; 

However, I get the following error:

The signature we signed for the request does not match the signature you provided. Check your key and signature method.

Do these parts of the code do the same? Did I miss something?

+10
source share
2 answers

The main problem is what you use createHash, which creates the hash, and not createHmac, which creates the HMAC.

createHash createHmac, , .

, :

chris /tmp/hmac $ cat node.js 
var crypto = require('crypto');
var key = 'abcd';
var data = 'wxyz';

function getHash(string){
    var hmac = crypto.createHmac('sha1', key);
    hmac.update(string); 
    return hmac.digest('binary'); 
};

process.stdout.write(getHash(data));

chris /tmp/hmac $ cat php.php 
<?php
$key = "abcd";
$data = "wxyz";
function __getHash($string)
{
    global $key;
    return hash_hmac('sha1', $string, $key, true); 
}

echo utf8_encode(__getHash($data));

chris /tmp/hmac $ node node.js | base64
WsOKw4xgw4jDlFHDl3jDuEPDuCfCmsOFwoDCrsK/w6ka
chris /tmp/hmac $ php php.php | base64
WsOKw4xgw4jDlFHDl3jDuEPDuCfCmsOFwoDCrsK/w6ka
+6

, hash_hmac true. , Chris Javascript.

, :

 $sign = hash_hmac('sha512', $post_data, $secret);

, nodejs:

const crypto = require("crypto");

function signHmacSha512(key, str) {
  let hmac = crypto.createHmac("sha512", key);
  let signed = hmac.update(Buffer.from(str, 'utf-8')).digest("hex");
  return signed
}

, hash_hmac ( , true), , PHP :

TRUE . FALSE .

node.js, digest('hex'), .

+9

All Articles