To generate an authentication header for an api connection, my code should follow these steps:
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?
答案 0 :(得分:5)
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.