Reputation: 31
I need to convert the following PHP code in C#:
$hash = hash_hmac('SHA256',"ent",'key',true);
echo rtrim(strtr(base64_encode($hash), '+/', '-_'), '=');
I use the following C# code:(FROM HERE)
private static string hmacSHA256(String data, String key)
{
using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key))) {
byte[] a2 = hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
string a3 = Convert.ToBase64String(a2).ToString.Replace("+", "-").Replace("/", "_").Replace("=", "");
return a3;
}
}
But the results are not the same.
PHP results : Xt0hGF_wcArzx4urxfbHUpOp2eEXvtGTDekGtQw5JTo
c# results : FnM4gpRRlapTZcO5iAIlEXEqU5iFT1hYcmQ1rY7ZINE
Upvotes: 3
Views: 1561
Reputation: 18320
I just tested both your codes and they work fine. I passed abcdefgh
and secretkey
as parameters and they give the same result.
It would've been good if you checked your actual input before asking.
C# code (fiddle):
Console.WriteLine(hmacSHA256("abcdefgh", "secretkey"));
Outputs:
d2AI63oXm2Q5VDCCjLvBrwKr-gT6vZcizD6BCq1rRjc
PHP code (make the fiddle yourself):
<?php
$hash = hash_hmac('SHA256',"abcdefgh",'secretkey',true);
echo rtrim(strtr(base64_encode($hash), '+/', '-_'), '=');
?>
Outputs:
d2AI63oXm2Q5VDCCjLvBrwKr-gT6vZcizD6BCq1rRjc
Your issue resides elsewhere.
Upvotes: 2