Hashing a string vs Hashing a UInt8Array

别来无恙 提交于 2020-01-05 08:27:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!