Search code examples
phpalgorithmhexsignaturesha256

HMAC sha256 in PHP does not return output in hex and with dash (-)


I would like to generate a signature computed in PHP using hmac sha256 algoirthm. The output should be identical to c# as follows:

private static string CreateToken(string message, string secret)
{

      var encoding = new System.Text.UTF8Encoding();
      byte[] keyByte = encoding.GetBytes(secret);
      byte[] messageBytes = encoding.GetBytes(message);
      using (var hmacsha256 = new HMACSHA256(keyByte))
      {
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
        return BitConverter.ToString(hashmessage);
      }
}

Output:

26-FF-E2-E2-95-13-30-4F-96-D4-44-CB-69-21-06-57-B4-E4-4E-83-7B-7C-8E-89-47-C6-67-B3-44-59-4F-18

Solution

  • Output format for hash hmac sha256 on php is not exactly identical with c#. Here is example of php's hash hmac sha256: https://stackoverflow.com/a/2708000/3706717

    string '07a932dd17adc59b49561f33980ec5254688a41f133b8a26e76c611073ade89b' (length=64)

    You just need to convert it to c#'s format

    • add a dash every 2 character
    • transform to uppercase
    $string = '07a932dd17adc59b49561f33980ec5254688a41f133b8a26e76c611073ade89b';
    $string = strtoupper($string);
    $arr = str_split($string, 2);
    $string = implode("-", $arr);
    var_dump($string);
    

    output:

    string(95) "07-A9-32-DD-17-AD-C5-9B-49-56-1F-33-98-0E-C5-25-46-88-A4-1F-13-3B-8A-26-E7-6C-61-10-73-AD-E8-9B"

    assuming the plaintext and secret is the same, the output of both c# and php (transformed by code above) should be equal string.