Being new to PHP, I need to convert an array of bytes to a string that can be used in php functions; hash_hmac("sha256", $payload, $key, true)
$key will come from Guid, say {6fccde28-de32-4c0d-a642-7f0c601d1776} , which will be converted to an array of bytes. Since hash_hmac takes a string for both data and key, I need to convert this byte array without loss due to non-printable characters.
I am using the 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 the value into $key yields the same base64 output in both languages, leaving $key incorrect / different.
So how to convert $keyBytes to $key without data loss?