NodeJS hmac digest issue with accents

别来无恙 提交于 2019-12-10 03:26:47

问题


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!


回答1:


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);


来源:https://stackoverflow.com/questions/9463157/nodejs-hmac-digest-issue-with-accents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!