简体   繁体   中英

Create C# generated HMAC hash in Javascript

I have C# function below;

private string GetEncyptionData(string encryptionKey)
    {
        string hashString = string.Format("{{timestamp:{0},client_id:{1}}}", Timestamp, ClientId);
        HMAC hmac = HMAC.Create();
        hmac.Key = Guid.Parse(encryptionKey).ToByteArray();
        byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(hashString));
        string encData = Convert.ToBase64String(hash);
        return encData;
    }

I am trying to convert this code in Javascript. I found this library as helper.

Here is code I am using;

 <script>
            var timestamp = 1424890904;
            var client_id = "496ADAA8-36D0-4B65-A9EF-EE4E3659910D";
            var EncryptionKey = "E69B1B7D-8DFD-4DEA-824A-8D43B42BECC5";

            var message = "{timestamp:{0},client_id:{1}}".replace("{0}", timestamp).replace("{1}", client_id);

            var hash = CryptoJS.HmacSHA1(message, EncryptionKey);
            var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);       

             alert(hashInBase64);
        </script>

but code above is not generating same output from C# code. How can I achieve it in Javascript?

Your issue is due to your key. In C#, you're passing in a 16-byte array as the key. In CryptoJS, you're passing in a string which CryptoJS is interpreting as a passphrase, so it's going to generate a totally different key from that.

EDIT : Here's how to get the correct key in javascript:

If you convert your 16-byte key to Base64, in javascript you can do the following. It will generate a WordArray as the key, and use that key to generate your hash.

var keyBase64 = "eFY0EiMBZ0UBI0VniRI0Vg==";
var key = CryptoJS.enc.Base64.parse(keyBase64);
var hash = CryptoJS.HmacSHA1("Hello", key);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash); 
console.log(hashInBase64);

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