Search code examples
javascript.netsha1cryptojshmacsha1

Javascript sha1 + HMCASHA1 Crypto JS encryption for .Net code


Following is how the encyption has been done on backend useing .Net.

public static string ShaEncrypt(string input,string keyStr) {
     byte[] key = Encoding.ASCII.GetBytes(keyStr);
     HMACSHA1 myhmacsha1 = new HMACSHA1(key);
     byte[] byteArray = Encoding.ASCII.GetBytes(input);
     MemoryStream stream = new MemoryStream(byteArray);
     return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
}

For the same I need to do this in front end Javascript. I have tried by using google code for Crypto using sha1.

var hash = CryptoJS.SHA1(keyString);
var test = CryptoJS.enc.Base64.Stringify(hash);

But I am getting CryptoJS.enc as undefined. Please help me.


Solution

  • I forgot to include the core-min.js, enc-base64-min.js.

    Also below is the Javascript code to convert Hashed values.

    var key = CryptoJS.enc.Utf8.parse(apiSecret);                                       
    var prehash = CryptoJS.enc.Utf8.parse(apiKey);                                       
    var hash = CryptoJS.HmacSHA1(prehash, key);   
    return hash;