2013-01-10 26 views
1

我试图从.net成员资源提供程序在javascript函数中重现相同的hmacsha1哈希和base64编码。我试过使用加密-js并得到不同的结果。在.NET代码会出现乱码“测试”到“W477AMlLwwJQeAGlPZKiEILr8TA =”如何在javascript中重新创建.net成员hmacsha1哈希

这里的.NET代码

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

而这里的JavaScript方法我用加密的js尝试,不会产生相同的输出

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

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

回答

0
//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); 
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提到的,你的问题是编码。所以,你只需要通过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))); 
+0

他用'password'作为重点和消息。由于不同的编码('ASCII'而不是'Unicode'),你的解决方案只会给出正确的结果 - 这是真正的问题。 – Andreas

+0

你说得对。我不知何故完全错过了他如何确定关键(错误地)。 –

+0

.net方法是Umbraco中的现有函数,我无法修改,所以很不幸,我无法更改它。我只能尝试在JavaScript中复制它。 – MonkeyBonkey