diff --git a/README.md b/README.md index 1eb6d20..23222a5 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,7 @@ multihashing(buf, 'sha1') multihashing.digest(buf, 'sha1') // Use `.createHash(...)` for a `crypto.createHash` interface. +// NOTE: The interface does not support streaming and only exposes .update(buffer) and .digest(type) var h = multihashing.createHash('sha1') h.update(buf) h.digest() diff --git a/src/index.js b/src/index.js index 1624e61..5afa5a0 100644 --- a/src/index.js +++ b/src/index.js @@ -32,7 +32,26 @@ mh.createHash = function (func, length) { throw new Error('multihash function ' + func + ' not yet supported') } - return mh.functions[func]() + const fnc = mh.functions[func]() + + return { + update: (buf) => fnc.update(buf), + digest: (type) => { + let digest = fnc.digest() + + if (length) { + digest = digest.slice(0, length) + } + + let hash = multihash.encode(digest, func, length) + + if (type) { // e.x. .digest('hex') + return hash.toString(type) + } else { + return hash + } + } + } } mh.verify = function (hash, buf) { diff --git a/src/sha3.js b/src/sha3.js index b7a9695..4097eba 100644 --- a/src/sha3.js +++ b/src/sha3.js @@ -19,16 +19,17 @@ class Hasher { constructor (hashFunc, arg) { this.hf = hashFunc this.arg = arg - this.input = null + this.input = [] } update (buf) { - this.input = buf + this.input.push(buf) return this } digest () { - const input = this.input + const input = Buffer.concat(this.input) + this.input = null const arg = this.arg return Buffer.from(this.hf(input, arg), 'hex') } diff --git a/test/index.spec.js b/test/index.spec.js index ef59261..70040cf 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -71,6 +71,17 @@ describe('multihashing', () => { expect(multihashing.verify(output, input)).to.be.eql(true) } }) + + it(algo + ' stream', () => { + for (const test of tests[algo]) { + const input = Buffer.from(test[0]) + const output = Buffer.from(test[1], 'hex') + const slices = test[0].split('').map(Buffer.from) + const h = multihashing.createHash(algo) + slices.forEach(h.update) + expect(multihashing.verify(h.digest(), input)).to.be.eql(true) + } + }) } it('cuts the length', () => {