简体   繁体   English

nodej 中的 hash_hmac 密钥到等效的 php 代码

[英]hash_hmac secret key in nodej to equivalent php code

I have an example in nodejs that I want to do in php我在 nodejs 中有一个例子,我想在 php 中做


    var nonce = new Date().getTime();
        
    var postdata = postdata || {};
    postdata.nonce = nonce;
        
    var stringmessage = JSON.stringify(postdata);
    var signedMessage = new hmac("sha512", self.secret);
        
    signedMessage.update(stringmessage);
        
    var sign = signedMessage.digest('hex');

So my code is as far as I can workout would be this所以我的代码是我可以锻炼的就是这个

    $data['nounce'] = time();
    $dataJson = json_encode($data);

    $sign = dechex(hash_hmac('sha512', $data ,$this->getSecret()));

but if I try to connect to this I get this message when trying to connect但如果我尝试连接到此,我会在尝试连接时收到此消息

Warning: file_get_contents(https://www.example.com.au/api/quote/buy): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

so I am assuming this is connecting to the hash is not correct.所以我假设这是连接到哈希不正确。

Three things to change and it should work:改变三件事,它应该起作用:

  1. In your JavaScript you use "nonce" but in your PHP you use "nounce"在您的 JavaScript 中,您使用“nonce”,但在您的 PHP 中,您使用“nounce”
  2. In your PHP hash_hmac you pass $data as the second parameter but you should be passing $dataJson在您的 PHP hash_hmac 中,您将 $data 作为第二个参数传递,但您应该传递 $dataJson
  3. You don't need the dechex, hash_hmac "Returns a string containing the calculated message digest as lowercase hexits unless raw_output is set to true" from https://www.php.net/manual/en/function.hash-hmac.php您不需要 dechex,hash_hmac“除非 raw_output 设置为 true,否则返回包含计算的消息摘要的字符串作为小写十六进制”来自https://www.php.net/manual/en/function.hash-hmac.php

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

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