node.js - MD5 库的不同结果

标签 node.js npm hash md5

我需要使用 MD5 对一些数据进行哈希处理。我想测试差异库的性能。但是,我注意到我得到了相同数据的不同哈希值,具体取决于所使用的库:

Generating data...

Hashing data with 'md5' library...
         Hash: 1b37c84ebc8426e19d3b1797b6e320c6
         Duration: 0.848s

Hashing data with 'object-hash' library...
         Hash: f046296e8016b5632e6a1d1ebc885892
         Duration: 0.032s

Hashing data with 'create-hash' library...
         Hash: 1b37c84ebc8426e19d3b1797b6e320c6
         Duration: 0.023s

我希望两个库显示相同的哈希值。有任何想法吗?我的代码如下...

const generateData = () => {
    console.log('Generating data...')
    let data = "";
    for (let i = 0; i < 1000000; i++) {
        data += "1234567890";
    }
    console.log()    
    return data;
}

const convertToUInt8Array = (s) => {
    var result = [];
    for(var i = 0; i < s.length; i+=2)
    {
        result.push(parseInt(s.substring(i, i + 2), 16));
    }
    result = Uint8Array.from(result)
    return result;
}

const hashData = (name, hashingFunction, data) => {
    console.log(`Hashing data with '${name}' library...`)
    const start = new Date()
    const hash = hashingFunction(data)
    const end = new Date()
    console.log(`\t Hash: ${hash}`)
    const duration = (end - start) / 1000
    console.log(`\t Duration: ${duration}s`)
    console.log()
}

const hashWithMD5 = (data) => {
    const md5 = require('md5')
    return md5(data)
}

const hashWithObjectHash = (data) => {
    const objectHash = require('object-hash')
    return objectHash.MD5(data)
} 

const hashWithCreateHash = (data) => {
    const createHash = require('create-hash')
    const hash = createHash('md5')
    hash.update(data)
    return hash.digest('hex')
}

const data = generateData()
hashData('md5', hashWithMD5, data)
hashData('object-hash', hashWithObjectHash, data)
hashData('create-hash', hashWithCreateHash, data)

最佳答案

object-hash 对对象而不是字符串值进行哈希处理。 implementation前置

'string:' + string.length + ':'

到输入字符串并对其进行 MD5 哈希。您可以通过修改 hashWithCreateHash 来生成相同输入的哈希来确认这一点:

const hashWithCreateHash = (data) => {
    const createHash = require('create-hash')
    const hash = createHash('md5')
    hash.update(`string:${data.length}:${data}`) // instead of hash.update(data)
    return hash.digest('hex')
}
Hashing data with 'create-hash' library...
         Hash: f046296e8016b5632e6a1d1ebc885892
         Duration: 0.023s

关于node.js - MD5 库的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58982325/

相关文章:

node.js - 无限循环 Kafka Consumer

node.js - 使用 node.js 更新 Firebase - 我需要等待吗?

javascript - 如何仅将依赖项放入 yarn 的特定文件夹中?

node.js - 在树莓派3上npm安装 Electron 错误

windows - Windows 上的 Nodejitsu

java - 从 murmur3 Guava 中只获得正多头

javascript - 如何以编程方式打开我从 Electron DesktopCapurer.getSources 获得的窗口

node.js - nodejs fs 文件系统返回空对象

java - 哈希函数和哈希表

c++ - 散列一个无序的小整数序列