dongqia3502 2019-07-18 03:33 采纳率: 100%
浏览 96

Javascript返回功能与php pack功能不匹配

In my project, I need to create a hash secure string in the client(javascript) and send it to the server(php). The server checks valid hash secure string or not before doing another stuff.

But the problem is the secure hash string generated in javascript does not match with the secure hash string generated in PHP.

I've already tried this related solution but it does not seem to work in my case.

Here is my PHP code

$message = '123';
$secure_secret = 'e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4';
$pack = pack('H*', $secure_secret);
$hash = hash_hmac('SHA512', $message, $pack);
var_dump('pack: ' . pack('H*', $secure_secret));
var_dump('hash: ' . $hash);

The above echos these:

b"pack: åéú\e£\x1EÍ\x1AèOuʪGO:f?\x05ô"
"hash: 5a7c65c2d0ec43b9c5fc255f36518fa3e6083d40db848768309e272973c200c4f3085466fd852cffbd962ec54cd0bd716d0deee6d76899943875d8da56143585"

And here is the javascript code(I'm using locutus's pack function for js):

var message = '123';
var secure_secret = 'e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4';
var pack = pack('H*', $secure_secret);
var hash = crypto.createHmac('SHA512', pack).update(message);
console.log('pack: ' + pack);
console.log('hash: ' + hash)

Result:

pack: åéú£ÍèOuʪGO:f?ô
hash: 2ab66f2f2b79968549f2744f55ab50b6b3249812d5c45d54b7fb2b24ceb173e3437dc191150bb4d3972a81ec7ea420fb5b58d9e5d4c9ba567d85566410d7508f

But if I change the $secure_secret string with another simpler string, such as '321' then the results will be matched.

PHP:

$message = '123';
$secure_secret = '321';
$pack = pack('H*', $secure_secret);
$hash = hash_hmac('SHA512', $message, $pack);
var_dump('pack: ' . pack('H*', $secure_secret));
var_dump('hash: ' . $hash);

Result

"pack: 2\x10"
"hash: deefdd44d55c5fe786ed3f1c09e3b32f32459dd885a970fe01091fecc17ef12162080c011e58fb7cd2f420a070f48c27ba19be9b92f07081a6f7908536f3eed9"

Javascript:

var message = '123';
var secure_secret = '321';
var pack = pack('H*', $secure_secret);
var hash = crypto.createHmac('SHA512', pack).update(message);
console.log('pack: ' + pack);
console.log('hash: ' + hash)

Result:

pack: "2?"
hash: deefdd44d55c5fe786ed3f1c09e3b32f32459dd885a970fe01091fecc17ef12162080c011e58fb7cd2f420a070f48c27ba19be9b92f07081a6f7908536f3eed9

So how can I fix this? Thank you.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 C#读写EXCEL文件,不同编译
    • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
    • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
    • ¥15 扩散模型sd.webui使用时报错“Nonetype”
    • ¥15 stm32流水灯+呼吸灯+外部中断按键
    • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
    • ¥15 NX MCD仿真与博途通讯不了啥情况
    • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
    • ¥15 gradio的web端页面格式不对的问题
    • ¥15 求大家看看Nonce如何配置