gpt4 book ai didi

node.js - MD5 库的不同结果

转载 作者:行者123 更新时间:2023-12-02 16:17:29 28 4
gpt4 key购买 nike

我需要使用 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com