Frage

I'm using the standard node crypto library to generate an HMAC MD5 hash.

When I try and read the hash value, the object that's returned is a <SlowBuffer> instead of an expected String.

Below is a simplified example, but it gives the same result:

var crypto = require('crypto');
var hmac = crypto.createHmac('md5', 'KEY');

hmac.write('something');
hmac.end();

var hash = hmac.read();

console.log(hash);

//Outputs: <SlowBuffer 4c ec c5 6e 46 90 23 7a f1 2e 5a 78 35 21 6a 7a>

What is causing the hash type to be coerced into a SlowBuffer type? How can I avoid this coercion, or at the very least read the original value from the buffer?

If I set the encoding value of the hash via hmac.setEncoding() it simply encodes the value <SlowBuffer 4c ec c5 6e 46 90 23 7a f1 2e 5a 78 35 21 6a 7a> as a string in the given format. The same is true is I try and call toString('encoding') on the buffer itself.

War es hilfreich?

Lösung

After reading the crypto docs more carefully, it seems this is actually expected:

If no encoding is provided, then a buffer is returned.

As the digest() method is deprecated in favour of read() I'd skipped over this and had assumed a default encoding would be used if none were specified.

The solution was simply hmac.setEncoding('hex').

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top