nodeJS 缓冲区和加密库为不同的版本提供了不同的答案

nodeJS buffer and crypto libraries is giving different answers for different versions

我正在将一些代码从 node.v4 迁移到 Node.v8

const crypto = require('crypto');
var Buffer = require('buffer').Buffer
const buf = 
Buffer.from('4DB79D009E6E0F59BC67879BDE67F4CDD9E2582794F80CFFF30321C2BDF85CCD', 'hex');


const hash = crypto.createHmac('sha256',  buf.toString('binary'));
hash.update('Hello world');
console.log(hash.digest('base64'));

为什么这个输出在每个版本中都不同。节点 v4 的答案是正确的,因为我们已经使用它很多年了。

为了让您的代码正常工作,我不确定您是否已经意识到,但只需使用原始缓冲区即可。

const hash = crypto.createHmac('sha256',  buf);

在它提到的加密库中

This is here because many functions accepted binary strings without any explicit encoding in older versions of node, and we don't want to break them unnecessarily.

https://github.com/nodejs/node/blob/449d60df1c11935d50e30bcad2a9ff4f5b4e955b/lib/crypto.js#L30

function toBuf(str, encoding) {
  encoding = encoding || 'binary';
  if (typeof str === 'string') {
    if (encoding === 'buffer')
      encoding = 'binary';
    str = new Buffer(str, encoding);
  }
  return str;
}
exports._toBuf = toBuf;

现在

https://github.com/nodejs/node/blob/master/lib/internal/crypto/util.js#L38

function toBuf(str, encoding) {
  if (typeof str === 'string') {
    if (encoding === 'buffer' || !encoding)
      encoding = 'utf8';
    return Buffer.from(str, encoding);
  }
  return str;
}

对于 hmac,toBuf 只会用键调用,所以如果编码是 undefined 并且你提供了一个字符串,那么之前你会得到 new Buffer(str,"binary") 而现在你会得到 Buffer.from(str,"utf8")

以下提交提到了这些更改,我不确定为什么评论保持不变但替换为 utf。 https://github.com/nodejs/node/commit/b010c8716498dca398e61c388859fea92296feb3