Search code examples
javascriptc#hmaccryptojs

HMAC C# and JavaScript


Having trouble getting C# and Javascript to generate the same HMAC:

C#:

string data = String.Format("{0}{1}{2}{3}{4}{5}", APPId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String);

        var secretKeyBytes = Convert.FromBase64String(sharedKey);

        byte[] signature = Encoding.UTF8.GetBytes(data);

        using (HMACSHA256 hmac = new HMACSHA256(secretKeyBytes))
        {
            byte[] signatureBytes = hmac.ComputeHash(signature);                
            return (incomingBase64Signature.Equals(Convert.ToBase64String(signatureBytes), StringComparison.Ordinal));
        }

Produces: apZUyGrS23BcEd2q5guGS4uQWVvcCvaDXIjCrLn/Hp4=

Javascript:

var signatureRawData = "".concat(appId, requestHttpMethod, requestUri, requestTimeStamp, nonce, requestContentBase64String);

var hash = CryptoJS.HmacSHA256(signatureRawData, apiKey);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);

Produces: mFZyyKT03OOThRnt/9dG/0x+jRde3jCMvI6Rd0eKhEE=


Solution

  • Where is the apiKey in the c# code? Is it sharedKey? Is sercretKeyBytes a string, char[], or byte[]? I suspect secrtetKeyBytes is being converted to a string which is the cause of the issue.