这个实例将演示如何用 Visual Basic 2005 编程生成某个字符串的 MD5 哈希值 (Hash Values)。
打开 Visual Studio 2005。在文件 (File) 菜单上,单击新建项目 (New Project)。 在新建项目 (New Project) 对话框的模板 (Templates) 窗格中,单击 Windows 应用程序 (Windows Application)。在名称 (Name) 框中键入 MD5Hash,再单击确定 (OK)。
在 Toolbox 里选中 Label 控件,将其拖到 Form1 上。在 Properties 窗口将该 Label 的 Name 属性改为 lblSource,其 Text 属性改为 Enter a string。
在 Toolbox 里选中 TextBox 控件,将其拖到 Form1 上,放在 lblSource下。在 Properties 窗口将该 TextBox 的 Name 属性改为 txtSource。
在 Toolbox 里选中 Label 控件,将其拖到 Form1 上,放在 txtSource 下。在 Properties 窗口将该 Label 的 Name 属性改为 lblMD5,其 Text 属性改为 MD5 hash values for the string you entered。
在 Toolbox 里选中 TextBox 控件,将其拖到 Form1 上,放在 lblMD5 下。在 Properties 窗口将该 TextBox 的 Name 属性改为 txtMD5。
在 Toolbox 里选中 Button 控件,将其拖到 Form1 上,放在 txtMD5 下。在 Properties 窗口将该 Button 的 Name 属性改为 btnMD5,其 Text 属性改为 Compute MD5 Hash Values。
画面如下。

双击 btnMD5,进入代码编辑窗口。添加代码,使其如下:
Imports System
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
Private Sub btnMD5_Click(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
End Class
选择调试 (Debug) 菜单中的开始调试 (Start Debugging),运行该程序。或者直接按快捷键 F5 运行。
在第一个 TextBox 输入 "vb 2005" 会出现其 MD5 哈希值。结果画面如下。

提示
计算 MD5 哈希值是用 MD5CryptoServiceProvider().ComputeHash 这个方法。
由于 ComputeHash 方法需要传入的参数是 Byte 类型,而不是 String 类型。因此要将传入的数据先从字符串变成一个 Byte 数组。用 ASCIIEncoding.ASCII.GetBytes 这个函数,可以将一个字符串变成一个 Byte 数组。
用 ComputeHash 方法计算并返回一个 MD5 哈希值,该返回值也是 Byte 类型。通常我们会将这个返回值变成一个 16 进制的字符串。上面代码中 ByteArrayToString 函数的作用,就是将一个 Byte 数组转换成一个 16 进制的字符串。
用 StringBuilder.Append 方法进行字符串的连接。比之一般的字符串连接方法效率更高。
编者:woyouxian[at]gmail[点]com
参考:微软支持站点 --> How to compute and compare hash values by using Visual Basic .NET or Visual Basic 2005
时间:2006-12-24
新思路站长网志 站长学院网页教程与代码
新思路站长网志信息中心
新思路站长网志 logo收藏