2013-01-10 27 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