1

Following PHP lines works great, but I can't do such in Node

$secret_key = hash('sha256', XXXX, true);
$hash = hash_hmac('sha256', YYYY, $secret_key);

As documentation sais hash() returns raw binary data, but it seems like utf8 string. Trying to do such in Node.js

const secret = crypto.createHash('sha256')
const secret_key = secret.update(XXXX).digest('utf8')

const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update(YYYY).digest('hex')

So PHP's $hash and Node.js result are not the same. Have tried secret key with 'hex' with no success. How to reproduce it in Node exactly as in PHP?

0

2 Answers 2

2

If you leave out the encoding of the first digest altogether, then you get equal strings:

const secret = crypto.createHash('sha256')
const secret_key = secret.update('XXXX').digest()

const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update('YYYY').digest('hex')

console.log(result);

Corresponding PHP code:

<?php
$secret_key = hash('sha256', 'XXXX', true);
$hash = hash_hmac('sha256', 'YYYY', $secret_key);

echo $hash;
PHP:    c4888731de466cefaa5c831b54132d3d9384310eb1be36f77f3f6542266cb307
NodeJS: c4888731de466cefaa5c831b54132d3d9384310eb1be36f77f3f6542266cb307
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! There is no hash.digets() with 'utf8' in documentation, I was confused with `hash.update(/* 'utf8' */) nodejs.org/api/crypto.html#crypto_hash_digest_encoding
0

I guess your mistake is making node export your secret key as "utf8" instead of a hexadecimal representation.

In PHP your key seems to be presented as hex values as well.

Try using "hex" in the first case as well and see what happens:

const secret = crypto.createHash('sha256')
const secret_key = secret.update(XXXX).digest('hex')

const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update(YYYY).digest('hex')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.