Skip to content
This repository was archived by the owner on Aug 11, 2021. It is now read-only.

fix: .createHash() returning wrong hashes / not working #33

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
21 changes: 20 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
7 changes: 4 additions & 3 deletions src/sha3.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
}
Expand Down
11 changes: 11 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down