2014-04-04 52 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