Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string