From 2e4816ddf1f7d21d32c667c1a62c72eb8e6861b4 Mon Sep 17 00:00:00 2001 From: Volker Mische Date: Fri, 5 Jan 2018 13:20:09 +0100 Subject: [PATCH] hash: only pad when needed Only add padding if there are bytes pending. If the padding is added unconditionally then the hash changes on every `digest()` call. --- lib/hash/common.js | 6 ++++-- test/hash-test.js | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/hash/common.js b/lib/hash/common.js index c49f476..e2c0daa 100644 --- a/lib/hash/common.js +++ b/lib/hash/common.js @@ -45,8 +45,10 @@ BlockHash.prototype.update = function update(msg, enc) { }; BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert(this.pending === null); + if (this.pending !== null) { + this.update(this._pad()); + assert(this.pending === null); + } return this._digest(enc); }; diff --git a/test/hash-test.js b/test/hash-test.js index 6a36efc..b80979b 100644 --- a/test/hash-test.js +++ b/test/hash-test.js @@ -121,4 +121,17 @@ describe('Hash', function() { ] ]); }); + + it('should return the same digest in subsequent calls', function() { + var hashed = hash.sha256().update('abc'); + assert.equal( + hashed.digest('hex'), + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'); + assert.equal( + hashed.digest('hex'), + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'); + assert.equal( + hashed.digest('hex'), + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'); + }); });