PHP and C# HMAC SHA256

I need to convert the following php code in C#:

$res = mac256($ent, $key);
$result = encodeBase64($res);


function encodeBase64($data)
    $data = base64_encode($data);
    return $data;


function mac256($ent,$key)
    $res = hash_hmac('sha256', $ent, $key, true);//(PHP 5 >= 5.1.2)
    return $res;

I use the following C# code:

byte[] res = HashHMAC(ent, key);
string result = System.Convert.ToBase64String(res);


public byte[] HashHMAC(string ent, byte[] key)
   byte[] toEncryptArray =System.Text.Encoding.GetEncoding(28591).GetBytes(ent);

   HMACSHA256 hash = new HMACSHA256(key);
   return hash.ComputeHash(toEncryptArray);

The complete php source code available at this link

I also check this post hmac_sha256 in php and c# differ

and this one C# equivalent to hash_hmac in PHP

But the results are not the same.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s