Avatar of Des Kelly
Des Kelly
Flag for Ireland asked on

HMAC Conversion from PHP to C#


I have a script in PHP which generates a signed string for an API, and I need to convert it to C#.  The output is not matching somehow though, and so the API is returning a 401.  What am I missing?

signature = hash_hmac('sha256', 'GET' . _url . hash('sha256', "") . timestamp . nonce, $secret_key);

var signature = SignWithHMAC("GET" + _url + CreateHash("") + timestamp + nonce, secret_key);

 public static string SignWithHMAC(byte[] dataToSign, byte[] keyBody)
            var enc = Encoding.ASCII;
            HMACSHA256 hmac = new HMACSHA256(keyBody);

            byte[] buffer = dataToSign;
            return Convert.ToBase64String(hmac.ComputeHash(buffer)).Replace("-", "");

 public static byte[] CreateHash(byte[] data)
            SHA256 shaM = new SHA256Managed();
            byte[] result = shaM.ComputeHash(data);
            return result;

Is there any reason the two different hashing and hmac methods would return different results?


Avatar of undefined
Last Comment
Des Kelly

8/22/2022 - Mon
Bob Learned

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Des Kelly

Many thanks for this - using this method I was able to get my outputs to match.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy