Search code examples
javascripthashasp.net-membershipcryptojs

how to recreate the .net membership hmacsha1 hash in javascript


I'm trying to reproduce the same hmacsha1 hash and base64 encoding from .net membership provider in a javascript function. I've tried using crypto-js and am getting different results. The .net code will hash "test" into "W477AMlLwwJQeAGlPZKiEILr8TA="

Here's the .net code

string password = "test";
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);
string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));

And here's the javascript method I tried using crypto-js that does not produce the same output

var hash = CryptoJS.HmacSHA1("test", "");
var encodedPassword = CryptoJS.enc.Base64.stringify(hash);

How can I get my javascript hash to match the hash being generated from .net.


Solution

  • //not sure why crypt-js's utf16LE function doesn't give the same result
    //words = CryptoJS.enc.Utf16LE.parse("test");
    //utf16 = CryptoJS.enc.Utf16LE.stringify("test");
    
    function str2rstr_utf16le(input) {
      var output = [],
          i = 0,
          l = input.length;
    
      for (; l > i; ++i) {
        output[i] = String.fromCharCode(
          input.charCodeAt(i)        & 0xFF,
          (input.charCodeAt(i) >>> 8) & 0xFF
        );
      }
    
      return output.join('');
    }
    
    var pwd = str2rstr_utf16le("test");
    var hash = CryptoJS.HmacSHA1(pwd, pwd);
    
    var encodedPassword = CryptoJS.enc.Base64.stringify(hash);
    alert(encodedPassword);