net 中MD5加密函数,包含asp.net和vb.net

    技术2024-07-16  64

     

    一、asp.net方式:

    需要引入

    Imports Microsoft.VisualBasic Imports System.Management

    Function GetMd5(ByVal str As String, ByVal code As Int16) As String If code = 16 Then Return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").Substring(8, 16) Else '32位加密 Return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5") End If '注意编码UTF8、UTF7、Unicode等的选择 '是用System.Text.Encoding.UTF8.GetBytes(strSource) End Function

    二、vb.net方式

    需要引入

    Imports System.Management Imports System.Security.Cryptography Imports System.Text

    Function GetMd5(ByVal Mystr As String) As String ' Create a new instance of the MD5 object. Dim md5Hasher As MD5 = MD5.Create() ' Convert the input string to a byte array and compute the hash. 'Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(Mystr)) Dim data As Byte() = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(Mystr)) '注意此处将编码方式改为了UTF-8目的在于和asp.net的编码方式保持一致,不然同样的加密源字符串,结果不一致 ' Create a new Stringbuilder to collect the bytes ' and create a string. Dim sBuilder As New StringBuilder() ' Loop through each byte of the hashed data ' and format each one as a hexadecimal string. Dim i As Integer For i = 0 To data.Length - 1 sBuilder.Append(data(i).ToString("x2")) Next i ' Return the hexadecimal string. Return sBuilder.ToString() End Function

    最新回复(0)