MD5加密字符串的实现方法介绍
使用方法:
16位长度的md5加密 ,如: MD5("lob.cn",16)
32位长度的md5加密 ,如: MD5("lob.cn",32)
===============更多请关注乐博网lob.cn===============
Imports System.Security.Cryptography
Imports System.Text
Private 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
Dim Str_MD5 As String = ""
Select Case Code
Case 16 ‘选择16位字符的加密结果
For i = 4 To 11
Str_MD5 += Hex(Hashvalue(i)).ToLower
Next
Case Else ‘Code错误时或者选择32位字符加密时,返回全部字符串,即32位字符
For i = 0 To Hashvalue.Length - 1
Str_MD5 += Hex(Hashvalue(i)).ToLower
Next
End Select
MD5 = Str_MD5
End Function
方法二(2009-07-29在csdn论坛上看到,乐博网补充上去,虽然是换汤不换药...):
导入名空间
- VB.NET code
-
Imports System.Text Imports System.Security.Cryptography
-
代码如下:
Private Function SetMd5Pass(ByVal InPutString As String) As String Dim Key As MD5 = MD5.Create Dim Bytes() As Byte = Key.ComputeHash(Encoding.Default.GetBytes(InPutString)) Dim Sbuilter As New StringBuilder For i As Integer = 0 To Bytes.Length - 1 Sbuilter.Append(Bytes(i).ToString("x2")) Next Return Sbuilter.ToString End Function
1 Private Function SetMd5Pass(ByVal InPutString As String) As String 2 Dim Key As MD5 = MD5.Create 3 Dim Bytes() As Byte = Key.ComputeHash(Encoding.Default.GetBytes(InPutString)) 4 Dim Sbuilter As New StringBuilder 5 For i As Integer = 0 To Bytes.Length - 1 6 Sbuilter.Append(Bytes(i).ToString("x2")) 7 Next 8 Return Sbuilter.ToString 9 End Function