繁体   English   中英

hash_hmac 和 hex2bin PHP 函数到 NodeJS 的转录

[英]Transcription of hash_hmac and hex2bin PHP functions to NodeJS

我有一个 PHP 脚本,它使用 HMAC 和一个密钥来生成 hash。 它运作良好:

$payload = '1605697463367HELLO';
$key = '861bbfc01e089259091927d6ad7f71c8b46b7ee13499574e83c633b74cdc29e3b7e262e41318c8425c520f146986675fdd58a4531a01c99f06da378fdab0414a';
$expected_result = '82ef9a8178dcb4df0b71540fa06d7da826ecb26e1977e230bdc8c9d6f9f1af84';

print_r([
    hash_hmac('sha256', $payload, $key),
    hash_hmac('sha256', $payload, hex2bin($key)),
    $expected_result
]);
/*
Array
(
    [0] => 466d4640b64eecc71e8a2dbd3bafdda0118295e07214e7a7845189699fcf7aa5
    [1] => 82ef9a8178dcb4df0b71540fa06d7da826ecb26e1977e230bdc8c9d6f9f1af84
    [2] => 82ef9a8178dcb4df0b71540fa06d7da826ecb26e1977e230bdc8c9d6f9f1af84
)
GOOD! [1] matches [2]!
*/

现在我需要把它翻译成 NodeJS。 我尝试了这些解决方案但没有成功:

const crypto = require('crypto');
const { TextEncoder } = require('util');
const { HmacSHA256 } = require('crypto-js');
const hex2bin = str => str.match(/.{1,2}/g).reduce((str, hex) => str += String.fromCharCode(parseInt(hex, 16)), '');

const payload = '1605697463367HELLO';
const key = '861bbfc01e089259091927d6ad7f71c8b46b7ee13499574e83c633b74cdc29e3b7e262e41318c8425c520f146986675fdd58a4531a01c99f06da378fdab0414a';
const expected_result = '82ef9a8178dcb4df0b71540fa06d7da826ecb26e1977e230bdc8c9d6f9f1af84';

console.log([
    crypto.createHmac('SHA256', key).update(payload).digest('hex'),
    crypto.createHmac('SHA256', hex2bin(key)).update(payload).digest('hex'),
    HmacSHA256(payload, key).toString(),
    HmacSHA256(payload, hex2bin(key)).toString(),
    HmacSHA256((new TextEncoder()).encode(payload), key).toString(),
    HmacSHA256((new TextEncoder()).encode(payload), hex2bin(key)).toString(),
    expected_result
]);
/*
[ '466d4640b64eecc71e8a2dbd3bafdda0118295e07214e7a7845189699fcf7aa5',
  'ccaa5b655b83f958eb8639e3fe8e6d0a2933b00779f5b84772bec89ba59a31d0',
  '466d4640b64eecc71e8a2dbd3bafdda0118295e07214e7a7845189699fcf7aa5',
  'ccaa5b655b83f958eb8639e3fe8e6d0a2933b00779f5b84772bec89ba59a31d0',
  '7f618537b8994815ac5a2ca347bc13709b7ccd722565832e800c9f824c1f722c',
  'e438ef17a0307ce1b9b42ed3f892f0009027879d21fa70c38175826f981d0eca',
  '82ef9a8178dcb4df0b71540fa06d7da826ecb26e1977e230bdc8c9d6f9f1af84' ]
BAD! no log matches the last!
*/

我想念什么? 谢谢你的帮助

编辑:添加了 PHP 的日志,没有 hex2bin 作为密钥

@svgta 指出,JS 中的 hex2bin function 可能已损坏。 我在 web 的某个地方找到了它,但它确实坏了。

这是对我有用的 hex2bin function(在这里找到https://stackoverflow.com/a/65160900/2030095

const hex2bin = hex => {
    const length = hex.length / 2;
    const result = new Uint8Array(length);
    for (let i = 0; i < length; i += 1) {
        result[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
    }
    return result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM