HMAC C#和JavaScript

时间:2016-04-04 20:45:08

标签: javascript c# hmac cryptojs

无法让C#和Javascript生成相同的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));
        }

产生: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);

产生:mFZyyKT03OOThRnt / 9dG / 0x + jRde3jCMvI6Rd0eKhEE =

1 个答案:

答案 0 :(得分:0)

c#代码中的apiKey在哪里?它是sharedKey吗? sercretKeyBytes是字符串,char []还是byte []?我怀疑将secrtetKeyBytes转换为导致问题的字符串。