关于ASP,ASP.NET,VB.NET里的MD5加密函数

来源:互联网 发布:java 超时控制 编辑:程序博客网 时间:2024/05/20 21:45
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
ASP中,我们使用过如动网论坛等用的ASPMD5函数加密出的字符串则如:
1165d25d8cd021d5

而在ASP.NET中下面的方法:
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password.Text,"MD5")
进行MD5加密出来的结果却是:
12C403B91165D25D8CD021D5F9B5BB7F

究其原因,是因为,在ASP中的MD5函数是使用了32位MD5 Hashvalue中的第9~25位再变小写作为密文。知道这个原因,把ASP.NET的结果稍加处理就可以用来比较老数据库中的密码字串了。
ASPMD5函数中第353、354行:
'MD5 = LCase(WordToHex(a) & WordToHex(b) & WordToHex(c) & WordToHex(d))
MD5=LCase(WordToHex(b) & WordToHex(c)) 'I crop this to fit 16byte database password :D
第一句是取全部的32位密文,第二句则是取中间第9~25位为16位密文。

到了VB.NET问题又来了,在VB.NET里,无法用到System.Web.Security名称空间,无法用上面简单的办法进行MD5加密。故我写了下面这个函数来处理:

VB.NET:
'MD5 加密函数
Public Shared Function MD5(ByVal strSource As String, ByVal Code As Int16) As String
'这里用的是ascii编码密码原文,如果要用汉字做密码,可以用UnicodeEncoding,但会与ASP中的MD5函数不兼容
Dim dataToHash As Byte() = (New System.Text.ASCIIEncoding).GetBytes(strSource)
Dim hashvalue As Byte() = CType(System.Security.Cryptography.CryptoConfig.CreateFromName("MD5"), System.Security.Cryptography.HashAlgorithm).ComputeHash(dataToHash)
Dim i As Integer
Select Case Code
Case 16 '选择16位字符的加密结果
For i = 4 To 11
MD5 = Hex(hashvalue(i)).ToLower
Next
Case 32 '选择32位字符的加密结果
For i = 0 To 15
MD5 = Hex(hashvalue(i)).ToLower
Next
Case Else 'Code错误时,返回全部字符串,即32位字符
For i = 0 To hashvalue.Length - 1
MD5 = Hex(hashvalue(i)).ToLower
Next
End Select
End Function

出处:AndyDavis BLOG

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击