【问题标题】:why does digest and digest('hex') result in different outputs?为什么digest 和digest('hex') 会导致不同的输出?
【发布时间】:2021-01-08 14:43:24
【问题描述】:

我有 2 段代码。

1ST ONE
const hash1 = (data) => createHash('sha256').update(data).digest('hex');
var a1 = hash1("A");
var b1 = hash1("B");
console.log(hash1(a1+b1));

2ND ONE
const hash2 = (data) => createHash('sha256').update(data).digest();
var a2 = hash2("A");
var b2 = hash2("B");
console.log(hash2(Buffer.concat([a2,b2])).toString('hex'));

他们为什么打印不同的结果?

digest('hex')digest() 相同,但格式不同,但仍然相同。那么,为什么我在控制台中得到不同的结果?当我总结十六进制而不是总结缓冲区时,它是 + 运算符吗?为什么?

【问题讨论】:

    标签: javascript cryptography sha256 cryptojs


    【解决方案1】:

    hash.digest([encoding]) 的默认编码是utf-8utf-8 是一个可变长度编码系统。它只会使用尽可能多的字节来表示每个字符(介于 1-4 个字节之间)。

    但是,当您指定hex 作为编码时,每个字符都存储为正好 2 个十六进制字符。

    当您在 utf-8 编码的哈希上调用 hash.toString('hex') 时,生成的十六进制表示等效于首先使用 hex 编码的哈希(如在 hash.digest('hex') 中)。

    因此,即使hex 表示在每种情况下都相同,但实际的数据 是不同的。即:

    hash.digest() != hash.digest('hex'),但是

    hash.digest().toString('hex') == hash.digest('hex').

    【讨论】:

      【解决方案2】:

      digest('hex')digest() 在技术上不同

      请试试这个代码

      var crypto = require('crypto');
      
      const hash1 = (data) => crypto.createHash('sha256').update(data).digest('hex');
      var a1 = hash1("A");
      var b1 = hash1("B");
      
      //console.log(a1)
      //console.log(b1)
      
      
      console.log(hash1(a1+b1));
      
      const hash2 = (data) => crypto.createHash('sha256').update(data).digest();
      
      var a2 = hash2("A");
      var b2 = hash2("B");
      //console.log(a2.toString("hex"))
      //console.log(b2.toString("hex"))
      
      console.log(hash2(a2.toString("hex") + b2.toString("hex") ).toString("hex"));
      

      首先,您要附加两个hex 字符串并传递给hash1
      在第二个中,您将附加两个非十六进制字符串并传递给hash2

      Run Nodejs online

      【讨论】:

      • 是的,在第二个中我附加了 2 个非十六进制字符串,而是附加了 2 个缓冲区,但问题是缓冲区与十六进制相同,只是格式不同。对不对?
      • 不,缓冲区是原始 UTF-8 内容的缓冲区,当您在 console.log 中打印时,它会显示十六进制值,这意味着 digest('hex')digest() 在技术上有所不同
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 2011-10-31
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      相关资源
      最近更新 更多