1

我正在尝试在 javascript 函数中从 .net 成员资格提供程序中重现相同的 hmacsha1 哈希和 base64 编码。我试过使用 crypto-js 并得到不同的结果。.net 代码会将“test”散列到“W477AMlLwwJQeAGlPZKiEILr8TA="

这是.net代码

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

这是我尝试使用不会产生相同输出的crypto-js的javascript方法

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

如何让我的 javascript 哈希与从 .net 生成的哈希匹配。

4

2 回答 2

1
//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);
于 2013-01-11T02:22:16.450 回答
0

您没有在 .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));

编辑:正如@Andreas 提到的,你的问题是编码。因此,您只需在自己的代码中将 UTF 替换为 ANSI:

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)));   
于 2013-01-10T23:26:05.953 回答