Node JS crypto, cannot create hmac on chars with accents

北战南征 提交于 2019-11-30 17:51:04
Jonathan Lonowski

The default encoding used by the crypto module is usually 'binary'. So, you'll have to specify 'utf-8' via a Buffer to use it as the encoding:

var sig = hmac.update(new Buffer(str, 'utf-8')).digest('hex');

That's what the answer for the other question was demonstrating, just for the key:

var hmac = crypto.createHmac('sha1', new Buffer(secKey, 'utf-8'));

You can also use Buffer to view the differences:

new Buffer('äïë', 'binary')
// <Buffer e4 ef eb>

new Buffer('äïë', 'utf-8')
// <Buffer c3 a4 c3 af c3 ab>

[Edit]

Running the example code you provided, I get:

Sig:      094b2ba039775bbf970a58e4a0a61b248953d30b
Expected: 094b2ba039775bbf970a58e4a0a61b248953d30b

And, modifying it slightly, I get true:

var crypto = require('crypto');

function sig(str, key) {
  return crypto.createHmac('sha1', key)
    .update(new Buffer(str, 'utf-8'))
    .digest('hex');
}

console.log(sig('äïë', 'secret') === '094b2ba039775bbf970a58e4a0a61b248953d30b');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!