MonkeyBonkey
MonkeyBonkey

Reputation: 47871

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.

Upvotes: 1

Views: 805

Answers (2)

MonkeyBonkey
MonkeyBonkey

Reputation: 47871

//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);

Upvotes: 1

Grimace of Despair
Grimace of Despair

Reputation: 3506

You don't specify a key in .NET:

var secretKey = "";
var password = "test";

var enc = Encoding.ASCII;
System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(enc.GetBytes(secretKey));
hmac.Initialize();

byte[] buffer = enc.GetBytes(password);
var encodedPassword = Convert.ToBase64String(hmac.ComputeHash(buffer));

Edit: as @Andreas mentioned, your problem is the encoding. So you just need to replace UTF by ANSI in your own code:

string password = "test";
System.Security.Cryptography.HMACSHA1 hash = new System.Security.Cryptography.HMACSHA1();
hash.Key = Encoding.ASCII.GetBytes("");
string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.ASCII.GetBytes(password)));   

Upvotes: 0

Related Questions