PHP and C# HMAC raw mode vs string

Viewed 29

I am trying to reproduce a php hashing function in C# and don't get the same output. I have read a couple posts about converting php hmac to c# but not combining raw/binary mode with string output. The php function is

function createSignature($accessKey,$secretKey,$method,$timeStamp,$apiService){         
   $eSignKey   = 'api' . $secretKey;
   $eAccessKey = hash_hmac('sha256', $accessKey, $eSignKey, true);
   $eMethodKey = hash_hmac('sha256', $method, $eAccessKey, true);
   $eTimeKey   = hash_hmac('sha256', $timeStamp, $eMethodKey, true);
   $eServiceKey= hash_hmac('sha256', $apiService, $eTimeKey, true);

   $eSignString = $accessKey.'|'.$method.'|'.$timeStamp.'|'.$apiService.'|'.$eServiceKey;

   return $signature = hash_hmac('sha256', $eSignString, $eServiceKey,false);
}

I have been able to reproduce the php hash_hmac with string output (false for the 4th parameter) but when adding all the hmacs together I get a different output.

php output is: 01d094fb72ca6891a7434fa284300c1996d934b863718ba731ae8c3ad29f57a6

c# output is: c5b255433fa3e528d6bcffaf3ad5bd68034cc62cd0cbbb119d58dd7c9a063912

My c# function is

        static string CreateSignature(string accessKey, string secretKey, string method, string timeStamp, string apiService)
        {
            var eSignKey = "api" + secretKey;
            var eSignKeyBinary = Encoding.UTF8.GetBytes(eSignKey);

            var eAccessKey = HashHmac(accessKey, eSignKeyBinary);
            var eMethodKey = HashHmac(method, eAccessKey);
            var eTimeKey = HashHmac(timeStamp, eMethodKey);
            var eServiceKey = HashHmac(apiService, eTimeKey);

            var eSignString = accessKey + '|' + method + '|' + timeStamp + '|' + apiService;


            var signature = HashHmacString(eSignString, eServiceKey);

            return signature;
        }

        private static byte[] HashHmac(string message, byte[] secret)
        {
            Encoding encoding = Encoding.ASCII;

            using (HMACSHA256 hmac = new HMACSHA256(secret))
            {
                var msg = encoding.GetBytes(message);
                var hash = hmac.ComputeHash(msg);

                return hash;
            }
        }

        private static string HashHmacString(string message, byte[] secret)
        {
            Encoding encoding = Encoding.ASCII;

            using (HMACSHA256 hmac = new HMACSHA256(secret))
            {
                var msg = encoding.GetBytes(message);
                var hash = hmac.ComputeHash(msg);

                return BitConverter.ToString(hash).ToLower().Replace("-", string.Empty);
            }
        }
0 Answers
Related