我正在将旧的ASP / MysqL webapp更新为ASP.NET / MS sql.
我们希望保持旧网站的登录在新应用中运行.
不幸的是,密码使用MysqL的password()函数存储在MysqL DB中.
是否可以在.NET或.NET中模拟MysqL的password()函数
MS sql?
任何帮助/链接表示赞赏.
解决方法
根据MysqL文档,该算法是双SHA1哈希.在检查MysqL源代码时,您会在libMysqL / password.c中找到一个名为make_scrambled_password()的函数.该功能定义如下:
/* MysqL 4.1.1 password hashing: SHA conversion (see RFC 2289,3174) twice applied to the password string,and then produced octet sequence is converted to hex string. The result of this function is used as return value from PASSWORD() and is stored in the database. SYNOPSIS make_scrambled_password() buf OUT buffer of size 2*SHA1_HASH_SIZE + 2 to store hex string password IN NULL-terminated password string */ void make_scrambled_password(char *to,const char *password) { SHA1_CONTEXT sha1_context; uint8 hash_stage2[SHA1_HASH_SIZE]; MysqL_sha1_reset(&sha1_context); /* stage 1: hash password */ MysqL_sha1_input(&sha1_context,(uint8 *) password,(uint) strlen(password)); MysqL_sha1_result(&sha1_context,(uint8 *) to); /* stage 2: hash stage1 output */ MysqL_sha1_reset(&sha1_context); MysqL_sha1_input(&sha1_context,(uint8 *) to,SHA1_HASH_SIZE); /* separate buffer is used to pass 'to' in octet2hex */ MysqL_sha1_result(&sha1_context,hash_stage2); /* convert hash_stage2 to hex string */ *to++= PVERSION41_CHAR; octet2hex(to,(const char*) hash_stage2,SHA1_HASH_SIZE); }
有了这个方法,你可以创建一个基本上做同样事情的.NET对应物.这就是我想出来的.当我运行SELECT PASSWORD(‘test’);对我的本地MysqL副本,返回的值是:
* 94BDCEBE19083CE2A1F959FD02F964C7AF4CFC29
根据源代码(再次在password.c中),开头的星号表示这是加密密码的MysqL 4.1后方法.例如,当我在VB.Net中模拟功能时,这就是我想出的:
Public Function GenerateMysqLHash(ByVal strKey As String) As String Dim keyArray As Byte() = Encoding.UTF8.GetBytes(strKey) Dim enc = New SHA1Managed() Dim encodedKey = enc.ComputeHash(enc.ComputeHash(keyArray)) Dim myBuilder As New StringBuilder(encodedKey.Length) For Each b As Byte In encodedKey myBuilder.Append(b.ToString("X2")) Next Return "*" & myBuilder.ToString() End Function
请记住,SHA1Managed()位于System.Security.Cryptography命名空间中.此方法返回与MysqL中的PASSWORD()调用相同的输出.我希望这对你有所帮助.
编辑:这是C#中的相同代码
public string GenerateMysqLHash(string key) { byte[] keyArray = Encoding.UTF8.GetBytes(key); SHA1Managed enc = new SHA1Managed(); byte[] encodedKey = enc.ComputeHash(enc.ComputeHash(keyArray)); StringBuilder myBuilder = new StringBuilder(encodedKey.Length); foreach (byte b in encodedKey) myBuilder.Append(b.ToString("X2")); return "*" + myBuilder.ToString(); }