简体   繁体   中英

HmacSHA256 returning different value in CryptoJs compared to .net/c#

I have recently migrated a Blazor app to.net5 which no longer supports HmacSHA256 and hence I am trying to use jsInterop workaround to get it working. However, I see the value generated by CryptoJs HmacSHA256 is not the same as c#.

Javascript version with CryptoJS:

    var getHmac = (privateKey, data) => {
        const key = window.CryptoJS.enc.Utf8.parse(privateKey);
        const utfData = window.CryptoJS.enc.Utf8.parse(data);
        const hmac = window.CryptoJS.HmacSHA256(utfData, key);
        return hmac;
    }
   const result = CryptoJS.enc.Hex.stringify(getHmac("123","abc");

And the c# version:

        public byte[] HmacSha256(string key, string data)
        {
            var keyArray = Encoding.UTF8.GetBytes(key);
            var hashAlgorithm = new HMACSHA256(keyArray);

            return hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(data));
        }
        public string ToHexString(IReadOnlyCollection<byte> array)
        {
            var hex = new StringBuilder(array.Count * 2);
            foreach (var b in array)
            {
                hex.AppendFormat("{0:x2}", b);
            }
            return hex.ToString();
        }
     var result = ToHexString(HmacSha256("123","abc"));

And they do not seem to have the same value. am I missing anything in the JavaScript implementation? Thanks

There is something strange... Testing in an online Javascript tester I get 8f16771f9f8851b26f4d460fa17de93e2711c7e51337cb8a608a0f81e1c1b6ae

// INIT
let privateKey = "123";
let data   = "abc";

document.getElementById("demo0").innerHTML = privateKey;
document.getElementById("demo1").innerHTML = data;

var getHmac = (privateKey, data) => {
    const key = CryptoJS.enc.Utf8.parse(privateKey);
    const utfData = CryptoJS.enc.Utf8.parse(data);
    const hmac = CryptoJS.HmacSHA256(utfData, key);
    return hmac;
}

const result = CryptoJS.enc.Hex.stringify(getHmac("123","abc"));

document.getElementById("demo2").innerHTML = result;

(I'm using crypto-js 4.0, the code is at https://codepen.io/gabrielizalo/pen/oLzaqx ),

Testing with C# under .NET Core 5.0 (see https://dotnetfiddle.net/IfLyRa ) (and 3.1) I get the same code.

Another online implementation ( https://www.freeformatter.com/hmac-generator.html#ad-output ) that says is using BouncyCastle returns the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM