生成 MD5 哈希值 (Hash Values) 的代码实例

来源:互联网 发布:c语言音乐代码 编辑:程序博客网 时间:2024/04/30 06:48

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

Public Class Form1

    Private Sub btnMD5_Click1(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnMD5.Click
        Dim sSourceData As String
        Dim tmpSource() As Byte
        Dim tmpHash() As Byte

        sSourceData = Me.txtSource.Text
        'Create a byte array from source data.
        tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData)

        'Compute hash based on source data.
        tmpHash = New MD5CryptoServiceProvider().ComputeHash(tmpSource)

        Me.txtMD5.Text = ByteArrayToString(tmpHash)

    End Sub

    Private Function ByteArrayToString(ByVal arrInput() As Byte) As String
        Dim i As Integer
        Dim sOutput As New StringBuilder(arrInput.Length)
        For i = 0 To arrInput.Length - 1
            sOutput.Append(arrInput(i).ToString("X2"))
        Next
        Return sOutput.ToString()
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Debug.Print(Len(txtMD5.Text))
    End Sub
End Class 

提示

计算 MD5 哈希值是用 MD5CryptoServiceProvider().ComputeHash 这个方法。

由于 ComputeHash 方法需要传入的参数是 Byte 类型,而不是 String 类型。因此要将传入的数据先从字符串变成一个 Byte 数组。用 ASCIIEncoding.ASCII.GetBytes 这个函数,可以将一个字符串变成一个 Byte 数组。

用 ComputeHash 方法计算并返回一个 MD5 哈希值,该返回值也是 Byte 类型。通常我们会将这个返回值变成一个 16 进制的字符串。上面代码中 ByteArrayToString 函数的作用,就是将一个 Byte 数组转换成一个 16 进制的字符串。

StringBuilder.Append 方法进行字符串的连接。比之一般的字符串连接方法效率更高。