Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...