5

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I already do this, however won't array_map "just" produce another array? Outcome then still have to put together in a string?
You can use implode function to obtain a string as result. $strings = array_map("chr", $bytes); $string = implode(" ", $strings);
0

Please try this function to convert a GUID into a binary string:

function guidToBytes($guid) {
    $guid_byte_order = [3, 2, 1, 0, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14, 15];
    $guid = preg_replace("/[^a-zA-Z0-9]+/", "", $guid);
    $result = [];
    foreach ($guid_byte_order as $offset) {
        $result[] = hexdec(substr($guid, 2 * $offset, 2));
    }
    return $result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.