无法编写 Node.js 模拟 PHP 哈希检查
Can't write Node.js analog to PHP hash checking
下面的 PHP 行效果很好,但我不能在 Node
中这样做
$secret_key = hash('sha256', XXXX, true);
$hash = hash_hmac('sha256', YYYY, $secret_key);
作为文档 sais hash() returns 原始二进制数据,但它看起来像 utf8 字符串。尝试在 Node.js
中这样做
const secret = crypto.createHash('sha256')
const secret_key = secret.update(XXXX).digest('utf8')
const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update(YYYY).digest('hex')
所以PHP的$hash
和Node.jsresult
是不一样的。已尝试使用 'hex' 的密钥但没有成功。如何完全按照 PHP?
在 Node 中重现它
我猜你的错误是让节点将你的密钥导出为 "utf8" 而不是十六进制表示。
在 PHP 中,您的密钥似乎也显示为十六进制值。
在第一种情况下也尝试使用 "hex",看看会发生什么:
const secret = crypto.createHash('sha256')
const secret_key = secret.update(XXXX).digest('hex')
const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update(YYYY).digest('hex')
如果您完全省略第一个 digest
的编码,那么您会得到相同的字符串:
const secret = crypto.createHash('sha256')
const secret_key = secret.update('XXXX').digest()
const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update('YYYY').digest('hex')
console.log(result);
对应PHP代码:
<?php
$secret_key = hash('sha256', 'XXXX', true);
$hash = hash_hmac('sha256', 'YYYY', $secret_key);
echo $hash;
PHP: c4888731de466cefaa5c831b54132d3d9384310eb1be36f77f3f6542266cb307
NodeJS: c4888731de466cefaa5c831b54132d3d9384310eb1be36f77f3f6542266cb307
下面的 PHP 行效果很好,但我不能在 Node
中这样做$secret_key = hash('sha256', XXXX, true);
$hash = hash_hmac('sha256', YYYY, $secret_key);
作为文档 sais hash() returns 原始二进制数据,但它看起来像 utf8 字符串。尝试在 Node.js
中这样做const secret = crypto.createHash('sha256')
const secret_key = secret.update(XXXX).digest('utf8')
const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update(YYYY).digest('hex')
所以PHP的$hash
和Node.jsresult
是不一样的。已尝试使用 'hex' 的密钥但没有成功。如何完全按照 PHP?
我猜你的错误是让节点将你的密钥导出为 "utf8" 而不是十六进制表示。
在 PHP 中,您的密钥似乎也显示为十六进制值。
在第一种情况下也尝试使用 "hex",看看会发生什么:
const secret = crypto.createHash('sha256')
const secret_key = secret.update(XXXX).digest('hex')
const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update(YYYY).digest('hex')
如果您完全省略第一个 digest
的编码,那么您会得到相同的字符串:
const secret = crypto.createHash('sha256')
const secret_key = secret.update('XXXX').digest()
const hmac = crypto.createHmac('sha256', secret_key)
const result = hmac.update('YYYY').digest('hex')
console.log(result);
对应PHP代码:
<?php
$secret_key = hash('sha256', 'XXXX', true);
$hash = hash_hmac('sha256', 'YYYY', $secret_key);
echo $hash;
PHP: c4888731de466cefaa5c831b54132d3d9384310eb1be36f77f3f6542266cb307 NodeJS: c4888731de466cefaa5c831b54132d3d9384310eb1be36f77f3f6542266cb307