Being new to PHP I need to convert an array of bytes to a string that may be used in php function; hash_hmac("sha256", $payload, $key, true)
The $key
will originate from a Guid, say {6fccde28-de32-4c0d-a642-7f0c601d1776}
, that's converted to an array of bytes. As hash_hmac
takes a string for both data and key I need to convert this byte array without loss due to non-printable chars.
I'm using following PHP code:
function guidToBytes($guid) {
$guid_byte_order = [3,2,1,0,5,4,6,7,8,9,10,11,12,13,14,15];
$guid = preg_replace("/[^a-zA-Z0-9]+/", "", $guid);
$result = [];
for($i=0;$i<16;$i++)
$result[] = hexdec(substr($guid, 2 * $guid_byte_order[$i], 2));
return $result;
}
$payload = utf8_encode("Some data string");
$keyBytes = guidToBytes("6fccde28-de32-4c0d-a642-7f0c601d1776");
$key = implode(array_map("chr", $keyBytes));
$hash = hash_hmac("sha256", $payload, $key, true);
$result = base64_encode($hash);
Equivalent code in c#:
var g = Guid.Parse("6fccde28-de32-4c0d-a642-7f0c601d1776");
var key = g.ToByteArray();
var data = "Some data string";
var payload = Encoding.UTF8.GetBytes(data);
using(var ha = new HMACSHA256(key)) {
var hash = ha.ComputeHash(payload);
var result = Convert.ToBase64String(hash);
}
Substituting value in $key
will produce same base64
output in both languages, leaving $key
to be the thing that's wrong/differs.
So; how do I convert $keyBytes
to $key
without loss of data?
You can use the chr function in PHP
http://php.net/manual/en/function.chr.php
chr receive in input an int and return a corrispondent ascii char.
$strings = array_map("chr", $bytes);
$string = implode(" ", $strings);
I hope I was helpful
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With