3

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

jon xz
  • 31
  • 3
  • Could you show us how you call the methods as well, i.e. what data you pass to them? – Visual Vincent Aug 04 '17 at 09:13
  • Why so many close votes on this? IMO this is a valid question, and it's far better than most new user-questions you find around here. He shows us both the original code and his attempted conversion, and he shows us the expected and received output. What could possibly be missing other than how he call those methods?? – Visual Vincent Aug 04 '17 at 09:16

1 Answers1

2

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.

Visual Vincent
  • 18,045
  • 5
  • 28
  • 75