如何在javascript中重新创建.net成员身份hmacsha1哈希

如何在javascript中重新创建.net成员身份hmacsha1哈希,javascript,hash,asp.net-membership,cryptojs,Javascript,Hash,Asp.net Membership,Cryptojs,我试图在javascript函数中从.net成员资格提供程序复制相同的hmacsha1哈希和base64编码。我尝试过使用crypto js,得到了不同的结果。net代码将把“test”散列为“w477amllwwjqealgpzkielr8ta=” 这是.net代码 string password = "test"; HMACSHA1 hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); string en

我试图在javascript函数中从.net成员资格提供程序复制相同的hmacsha1哈希和base64编码。我尝试过使用crypto js,得到了不同的结果。net代码将把“test”散列为“w477amllwwjqealgpzkielr8ta=”

这是.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生成的哈希相匹配。

您在.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提到的,您的问题是编码。因此,您只需要在自己的代码中用ANSI替换UTF:

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

您没有在.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提到的,您的问题是编码。因此,您只需要在自己的代码中用ANSI替换UTF:

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

他使用
密码
作为密钥和消息。您的解决方案只会给出正确的结果,因为编码不同(
ASCII
而不是
Unicode
)-这才是真正的问题。您是对的。不知何故,我完全错过了他是如何(错误地)设置键的。net方法是Umbraco中现有的函数,我无法修改,所以很遗憾,我无法更改它。我只能尝试在javascript中复制它。所以看起来区别在于crypto js散列使用utf-8编码,而.net库使用utf-16编码。难道你不喜欢这种奇怪的东西吗?这不是你的错,但很容易让你耽误一天的时间吗?:)你的答案实际上就是解决方案吗?他使用
密码
作为密钥和消息。您的解决方案只会给出正确的结果,因为编码不同(
ASCII
而不是
Unicode
)-这才是真正的问题。您是对的。不知何故,我完全错过了他是如何(错误地)设置键的。net方法是Umbraco中现有的函数,我无法修改,所以很遗憾,我无法更改它。我只能尝试在javascript中复制它。所以看起来区别在于crypto js散列使用utf-8编码,而.net库使用utf-16编码。难道你不喜欢这种奇怪的东西吗?这不是你的错,但很容易让你耽误一天的时间吗?:)你的答案真的是解决方案吗?