3

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?

1
  • Are you 100% sure encryption key and timestamp are exact? That's what often tripped me up in the past.... Also compare values before and after the hash and again before and after the base 64 conversion to see where the differences may lie. Commented Feb 25, 2015 at 20:17

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Simply works great. I wish I would have Javascript equivalent of Guid.Parse(encryptionKey).ToByteArray(); but anyway I will convert it manually for now.
CryptoJS might have something that can do it - I didn't dig too much into their helper libraries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.