To generate an authentication header for an api connection, my code should follow these steps:
- Create a string of the form [unique]:[apikey].
- Convert string from step 1 to a byte array using UTF-8 encoding.
- Compute the SHA-256 hash for the byte array from step 2.
- 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?