我使用的是php 8.0.11,我必须生成一个SHA256加密API,我在邮递员中用javascipt代码在Pre-request脚本中测试这个messagesignature.When,它给出了正确的加密消息签名,当我在php中测试它时,我将脚本转换为php,它发送了一个不同的错误加密消息签名(密钥和消息是假的):
javascript代码(postman中的Pre-request脚本):
let msg='mymessage'
const hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256,"myapipkey");
hmac.update(msg);
const messageSignature = hmac.finalize().toString();
pm.globals.set("messageSignature",messageSignature);
console.log('messageSi:',pm.globals.get('messageSignature'))php代码:
$data_to_hash = "mymessage";
$data_hmac=hash('sha256', $data_to_hash);
$ctx = hash_init('sha256', HASH_HMAC, 'myapipkey');
hash_update($ctx, $data_hmac);
$result = hash_final($ctx);
echo $result;发布于 2021-11-08 09:38:09
只需对PHP代码进行简单更改,就可以得到正确的结果。
看起来你散列了两次(或者类似的东西!)
$data_to_hash = "mymessage";
$ctx = hash_init('sha256', HASH_HMAC, 'myapipkey');
hash_update($ctx, $data_to_hash);
$result = hash_final($ctx);
echo $result;在任何情况下,上述代码的输出都将是:
898786a1fa80da9b463c1c7c9045377451c40cf3684cbba73bdfee48cd3a5b8f它与JavaScript代码相同,都与这里给出的输出相匹配:
https://codebeautify.org/hmac-generator
With Algorithm = 'SHA256',Key = 'myapipkey‘和Plaintext = 'mymessage’。
https://stackoverflow.com/questions/69881208
复制相似问题