skip to Main Content

Below is the code of both C# and PHP, I need some help regarding it. I am trying to generate the authenticationKey which is in C# but want the convert in PHP. All is done but I don’t know how to implement [System.Text] in PHP as there is hash_hmac() in PHP but what might be the $string in the same function.

C# Version

var hmac = new System.Security.Cryptography.HMACSHA256();
var buffer = userName + accessKey + timeStamp + originUrl;
var hash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(buffer));
var authenticationKey = Convert.ToBase64String(hash);

PHP version

$hmac = hash_hmac('sha256', $string, $buffer);
$encoded = base64_encode($hmac);

Can anyone help me with that. It will be very helpful. Thanks.

3

Answers


  1. You may get the hex value, using unpack method:

    $value = unpack('H*', buffer);
    echo $value[1];
    
    Login or Signup to reply.
  2. In your c# code, you used a randomly generated key. Check the documentation:
    https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.hmacsha256?view=netframework-4.8#constructors

    HMACSHA256()

    Initializes a new instance of the HMACSHA256 class with a randomly generated key.

    HMACSHA256(Byte[])

    Initializes a new instance of the HMACSHA256 class with the specified key data

    Now the php documentation in comparison: https://www.php.net/manual/en/function.hash-hmac.php

    hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = FALSE ] ) : string
    

    You see, what you call buffer in php, is actually the key and what you call buffer in c# is the data you hash.

    So the$string should contain the data to be hashed.

    As per the conversion, you don’t need to get bytes in php: What is the PHP equivalent of this C# encoding code?

    Login or Signup to reply.
  3. I was also searching for this and atlast it was just a mistake of 1 small varibale, in the hash_hmac function pass the last value as true, this is will return raw output and when you convert it to base64 it will give the same output as the c# code.

    $buffer = $userName.$accessKey.$timeStamp.$originUrl;
    $hmac = hash_hmac('sha256', $buffer, $tokenSecret, true);
    $authenticationKey = base64_encode($hmac);
    

    Just in your c# function use the key, as shown in the code below

    var hmac = new System.Security.Cryptography.HMACSHA256();
    hmac.Key = System.Text.Encoding.UTF8.GetBytes(tokenSecret);
    

    In my code I have tokenSecret variable in bas64 form.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search