一、asp.net方式:
需要引入
Imports Microsoft.VisualBasic
Imports System.Management
Function GetMd5(ByVal str As String, ByVal code As Int16) As String<br /> If code = 16 Then<br /> Return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").Substring(8, 16)</p><p> Else '32位加密<br /> Return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5")<br /> End If<br /> '注意編碼UTF8、UTF7、Unicode等的選擇<br /> '是用System.Text.Encoding.UTF8.GetBytes(strSource) </p><p> End Function
二、vb.net方式
需要引入
Imports System.Management
Imports System.Security.Cryptography
Imports System.Text
Function GetMd5(ByVal Mystr As String) As String</p><p> ' Create a new instance of the MD5 object.<br /> Dim md5Hasher As MD5 = MD5.Create()</p><p> ' Convert the input string to a byte array and compute the hash.<br /> 'Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(Mystr))<br /> Dim data As Byte() = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(Mystr))<br /> '注意此處將編碼方式改為了UTF-8目的在於和asp.net的編碼方式保持一致,不然同樣的加密源字串,結果不一致</p><p> ' Create a new Stringbuilder to collect the bytes<br /> ' and create a string.<br /> Dim sBuilder As New StringBuilder()</p><p> ' Loop through each byte of the hashed data<br /> ' and format each one as a hexadecimal string.<br /> Dim i As Integer<br /> For i = 0 To data.Length - 1<br /> sBuilder.Append(data(i).ToString("x2"))<br /> Next i</p><p> ' Return the hexadecimal string.<br /> Return sBuilder.ToString()</p><p> End Function