Imports System.Security.Cryptography
Imports System.Text

Namespace Security
    Public Class Md5
        ''' <summary>
        ''' 获取字符串的MD5值
        ''' </summary>
        ''' <param name="str">需要求MD5的原文字符串</param>
        ''' <returns></returns>
        Public Shared Function GetStringMd5(str As String) As String
            Dim md5Hasher As New MD5CryptoServiceProvider()
            Dim data As Byte() = md5Hasher.ComputeHash(Encoding.UTF8.GetBytes(str))
            Dim fileMd5 As New StringBuilder()
            Dim i As Integer
            For i = 0 To data.Length - 1
                fileMd5.Append(data(i).ToString("X2"))
            Next

            Return fileMd5.ToString()
        End Function

        ''' <summary>
        ''' 获取文件的MD5值
        ''' </summary>
        ''' <param name="filepath">文件路径</param>
        ''' <returns></returns>
        Public Shared Function GetFileMd5(filepath As String) As String
            Dim md5Hasher As New MD5CryptoServiceProvider()
            Dim data As Byte() = md5Hasher.ComputeHash(IO.File.ReadAllBytes(filepath))
            Dim fileMd5 As New StringBuilder()
            Dim i As Integer
            For i = 0 To data.Length - 1
                fileMd5.Append(data(i).ToString("X2"))
            Next

            Return fileMd5.ToString()
        End Function
    End Class
End Namespace