dqu3974 2017-08-04 12:23
浏览 398
已采纳

php字符串作为字节数组,哈希然后base64编码

To generate an authentication header for an api connection, my code should follow these steps:

  1. Create a string of the form [unique]:[apikey].
  2. Convert string from step 1 to a byte array using UTF-8 encoding.
  3. Compute the SHA-256 hash for the byte array from step 2.
  4. Base64 encode the byte array computed in step 3; this string will be authentication key.

As far as I understand, strings in php are byte arrays, so my initial method looks like the following.

public function generateAuthKey()
{
    $unique = uniqid(); # unique string
    $string = $unique.':'.$this->apiKey; # step 1
    $string = utf8_encode($string); # step 2 ?
    $hash = hash('sha256', $string); # step 3
    $base64 = base64_encode($hash); # step 4

    return $base64;
}

My application which tries to connect using this auth key will receive a 403 error.

Does my code above complete the required steps (and perhaps there is an error in my api key) or is there some other way in php of following the steps to create the auth key?

  • 写回答

1条回答 默认 最新

  • doudaifu6083 2017-08-04 12:31
    关注

    Yes, strings in PHP are already byte arrays. And unless your $string contains any non-ASCII characters, it's also already valid UTF-8 (UTF-8 is a superset of ASCII); so you can skip the "encode as UTF-8" step.

    Likely the algorithm is expecting the output of the hash to be binary, which you're then supposed to convert to base 64. By default hash returns hex values, not binary. For that you need to set its 3rd parameter. In summary:

    $unique = uniqid();
    $string = $unique . ':' . $this->apiKey;
    $hash   = hash('sha256', $string, true);
    $base64 = base64_encode($hash);
    

    Of course, what you're supposed to do with $unique I don't know. Likely you're supposed to send that value together with the request as well, otherwise there's no way the server can validate the hash.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TMC2209串口模式下读取不到寄存器的值串口助手蓝色字体是发过去的消息,绿色字体是收到的消息,第二行发送读取寄存器的指令但是没有读取到寄存器的值串口助手如下图:接线如下图,如何解决?
  • ¥30 itest不允许查看成绩怎么办
  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏