以下php行效果很好,但是我在节点
中做不到$secret_key = hash('sha256', XXXX, true);
$hash = hash_hmac('sha256', YYYY, $secret_key);
作为文档,sais hash((返回原始二进制数据,但看起来像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')
SO PHP的$hash
和Node.js result
不一样。尝试使用"十六进制"的秘密钥匙,没有成功。如何完全像php中的节点一样复制它?
如果您完全遗漏了第一个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
我猜你的错误是使节点导出您的秘密键为" utf8",而不是十六进制表示。
在PHP中,您的钥匙似乎也以十六进制值的形式出现。
在第一种情况下也尝试使用"十六进制",看看会发生什么:
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')