Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS hmac digest issue with accents

Tags:

node.js

hmac

I'm doing a side by side comparison with Ruby, PHP and NodeJS for the following code, getting an incorrect response in NodeJS using the crypto module.

PHP

hash_hmac('sha256', 'text', 'á');

Ruby

OpenSSL::HMAC.hexdigest('sha256', 'á', 'text')

NodeJS

var signer = crypto.createHmac('sha256', 'á');
var expected = signer.update("text").digest('hex');

Both Ruby and PHP return 34b3ba4ea7e8ff214f2f36b31c6a6d88cfbf542e0ae3b98ba6c0203330c9f55b, while, NodeJS returns 7dc85acba66d21e4394be4f8ead2a327c9f1adc64a99c710c98f60c425bd7411. I noticed that, if I try with utf8_encode('á') in PHP, it actually gives me the result Node expects.

I'm loading the accented text in Node from a file, like so:

JSON.parse(fs.readFileSync('keys.js', 'utf8'));

How would I go about changing my code in Node to get the resulting hash that both PHP and Ruby present?

Thanks!

like image 731
Roberto Avatar asked Feb 27 '12 10:02

Roberto


1 Answers

This code will give you the correct result:

var crypto = require('crypto');

var signer = crypto.createHmac('sha256', new Buffer('á', 'utf8'));
var result = signer.update("text").digest('hex');
console.log(result);
like image 97
Vadim Baryshev Avatar answered Nov 02 '22 15:11

Vadim Baryshev