我正在尝试使用 NodeJS Crypto 库验证数据完整性。它需要计算 JSON 字符串的 Hmac。
经过一些测试,我已经能够找到问题:只要它包含一个 unicode 字符就会发生。例如:
var hasher = crypto.createHmac("sha256", 'secret_key');
hasher.write('{"timezone":"(GMT-05:00) Eastern Time (US \u0026 Canada)"}');
hasher.end();
var calculatedHmac = new Buffer(hasher.read(), 'utf8').toString('base64');
console.log(calculatedHmac);
但是,这会返回错误的 hmac。PHP 中的相同代码与我从第三方服务收到的签名相匹配:
$data = '{"timezone":"(GMT-05:00) Eastern Time (US \u0026 Canada)"}';
$calculated_hmac = base64_encode(hash_hmac('sha256', $data, 'secret_key', true));
var_dump($calculated_hmac); // Result is correct here
如果我删除 NodeJS 有效负载中的“\u0026”,那么我会得到与 PHP 相同的正确结果。
我在这里做错了吗?
谢谢!