Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/internal/crypto/hash.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,11 @@ Hmac.prototype.digest = function digest(outputEncoding) {
return ret;
};

Hmac.prototype._flush = Hash.prototype._flush;
Hmac.prototype._flush = function _flush(callback) {
this.push(this[kHandle].digest());
this[kState][kFinalized] = true;
callback();
};
Hmac.prototype._transform = Hash.prototype._transform;

// Implementation for WebCrypto subtle.digest()
Expand Down
3 changes: 3 additions & 0 deletions src/crypto/crypto_hmac.cc
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ void Hmac::HmacDigest(const FunctionCallbackInfo<Value>& args) {
return ThrowCryptoError(env, ERR_get_error(), "Failed to finalize HMAC");
}
hmac->ctx_.reset();
} else {
// The context has already been finalized; never emit unwritten bytes.
buf.len = 0;
}

Local<Value> ret;
Expand Down
20 changes: 20 additions & 0 deletions test/parallel/test-crypto-hmac.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,26 @@ for (let i = 0, l = rfc4231.length; i < l; i++) {
}
}

// Calling digest() after the Hmac has already been used as a stream must
// return an empty buffer (the DEP0206 repeat-digest guard), not uninitialized
// stack memory. The stream itself must still produce the correct digest.
// See: https://github.com/nodejs/node/issues/28245
{
const key = 'key';
const data = 'some data to hash';

const streamHmac = crypto.createHmac('sha256', key);
streamHmac.end(data);
const streamDigest = streamHmac.read();

// digest() after the stream already finalized must not return garbage.
assert.deepStrictEqual(streamHmac.digest(), Buffer.from(''));

// Sanity check: the stream itself produced the correct digest.
const expected = crypto.createHmac('sha256', key).update(data).digest();
assert.deepStrictEqual(streamDigest, expected);
}

// Test HMAC-MD5/SHA1 (rfc 2202 Test Cases)
const rfc2202_md5 = [
{
Expand Down
Loading