2014-04-04 54 views
1

我在asp.net中創建了一個wesite並使用ms-sql數據庫來保存記錄。現在想要在node.js應用程序中進行轉換。並希望使用相同的SQL數據庫。在asp.net應用程序中,我已經爲註冊用戶加密了密碼。以下是代碼。Node.js密碼加密與Asp.Net相同

public static string CreateHash(string unHashed) 
    { 
     System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); 
     byte[] data = System.Text.Encoding.ASCII.GetBytes(unHashed); 
     data = x.ComputeHash(data); 
     return System.Text.Encoding.ASCII.GetString(data); 
    } 


    public static bool MatchHash(string HashData, string HashUser) 
    { 
     HashUser = CreateHash(HashUser); 
     if (HashUser == HashData) 
      return true; 
     else 
      return false; 

    } 

現在的問題是,我如何在node.js中使用相同的加密。所以當節點應用程序準備就緒時,舊用戶也可以進行登錄。它只有在節點應用程序也可以使用我在asp.net中使用的相同加密時纔有可能。

對於節點我創建了所有環境並使用mssql模塊進行數據庫通信。請幫我解決這個問題。謝謝!!

回答

0

如果您對安全性認真,不要再使用MD5。

根據您的評論和代碼,我擔心在最初的ASP.net代碼中存在「數據丟失」。 讓我們再看看CreateHash功能,我添加了註釋:

public static string CreateHash(string unHashed) 
    { 
     System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); 

     // Convert unHashed string to bytes using ASCII coding 
     byte[] data = System.Text.Encoding.ASCII.GetBytes(unHashed); 

     // Compute MD5 hash from bytes 
     data = x.ComputeHash(data); 

     // Decode MD5 resulting bytes as ASCII 
     return System.Text.Encoding.ASCII.GetString(data); 
    } 

最後一行讓我困惑,它的解碼,就好像他們是ASCII從MD5函數接收的字節,但是這是不正確的假設。並且在註釋中給出的結果編碼字符串包含很多「?」。

下一頁Node.js的代碼會做,除了編碼類似使用十六進制,而不是ASCII字符串:

var crypto = require('crypto') 

function createHash(data) { 
    return crypto.createHash('md5').update(data, 'ascii').digest('hex') 
} 

要效仿「字節ASCII」你可以嘗試.digest(「二進制」),而不是十六進制。如果它沒有給你期望的,那麼你必須做一個單獨的從十六進制到ASCII轉換的「轉換」步驟。 (我沒有經驗足以給你優雅的解決方案,以後者)

+0

感謝您的回覆,但它似乎不工作。我有使用字符串「testpassword」。 .Net返回「?k * ??#?N ?? 9?l」和節點返回「e16b2ab8d12314bf4efbd6203906ea6c」。節點也應該返回與.net函數相同的值。 – user1951489

+0

@ user1951489我已經更新了答案,因爲您給了我更多關於評論中發生的事情的線索。 – alandarev

+0

如果使用.digest('binary'),則節點返回「ák*,Ñ#¶¿NûÖ9♠êl」。它應該返回「?k * ??#?N ?? 9?l」 – user1951489