Link to home
Start Free TrialLog in
Avatar of Des Kelly
Des KellyFlag for Ireland

asked on

HMAC Conversion from PHP to C#

Hi,

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?

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

C#
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);
            hmac.Initialize();

            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?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Des Kelly

ASKER

Many thanks for this - using this method I was able to get my outputs to match.