问题
I'm comparing the performance of two MD5 libraries. When I send them both a string, they return the same hash:
Hashing data with 'md5' library...
Hash: d8b1e68f2f36743cdf302ed36f9347dc
Duration: 0.003s
Hashing data with 'create-hash' library...
Hash: d8b1e68f2f36743cdf302ed36f9347dc
Duration: 0.003s
However, when I send them the same UInt8Array, they give me different hashes:
Hashing data with 'md5' library...
Hash: 77fcf76d3f8c6a0f685f784d7ca6c642
Duration: 0.001s
Hashing data with 'create-hash' library...
Hash: 0ee0646c1c77d8131cc8f4ee65c7673b
Duration: 0s
Why does this happen?
const hashData = (name, hashingFunction, data) => {
console.log(`\t Hashing data with '${name}' library...`)
const start = new Date()
const hash = hashingFunction(data)
const end = new Date()
console.log(`\t\t Hash: ${hash}`)
const duration = (end - start) / 1000
console.log(`\t\t Duration: ${duration}s`)
console.log()
}
const runHashes = (data) => {
const hashWithMD5 = (data) => {
const md5 = require('md5')
return md5(data)
}
const hashWithCreateHash = (data) => {
return require('create-hash')('md5').update(data).digest('hex')
}
hashData('md5', hashWithMD5, data)
hashData('create-hash', hashWithCreateHash, data)
}
console.log('*** Running hashes on strings... *** \n')
runHashes("I want you to hash me...")
console.log('*** Running hashes on UInt8Array... *** \n')
runHashes(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))
回答1:
Based on the md5 module API documentation, the hashing function accepts either a String
or a Buffer
. Your input of Uin8Array
is neither, so I'm guessing the behavior of the hashing is going to be relatively undefined in comparison to the well-defined output given correctly typed input.
来源:https://stackoverflow.com/questions/58982969/hashing-a-string-vs-hashing-a-uint8array