Creating an MD5 Hash of a String

This demo illustrates how to use the MD5CryptoServiceProvider class, which performs an MD5 hash. This class is part of the .NET Framework, and hence can be utilized through an ASP.NET Web page, as shown in this demo.

The MD5CryptoServiceProvider class takes as input an array of bytes and produces a hashed array containing 16 bytes. These bytes can contain values that do not clearly map to characters that can be properly displayed on a Web page; therefore, when using this demo you'll note the actual values of each of the 16 array elements are displayed, as opposed to the string representation of the 16 bytes.


Enter a string:


Source Code
<%@ Import Namespace="System.Security.Cryptography" %>
<%@ Import Namespace="System.Text" %>
<script language="VB" runat="server">
  Sub DisplayEncryptedText(sender as Object, e as EventArgs)
    If Page.IsValid then
      Dim md5Hasher as New MD5CryptoServiceProvider()
    
      Dim hashedDataBytes as Byte()   
      Dim encoder as New UTF8Encoding()

      hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(txtPassword.Text))    
    
      ltlResults.Text = "<b>Encrypted Results</b><br /> The results are encrypted into " & _
              "an array of 16 bytes.  These 16 bytes contain the values:<p><ul>"
    
      Dim b as Byte
      For Each b in hashedDataBytes
	    ltlResults.Text &= "<li>" & b & "</li>"
      Next b
      
      ltlResults.Text &= "</ul>"    
    End If
  End Sub  
</script>

<form runat="server">
  Enter a string:
  <asp:TextBox id="txtPassword" runat="server" />
  <asp:RequiredFieldValidator runat="server" ControlToValidate="txtPassword"
           Display="Dynamic" ErrorMessage="<i>You must provide a value here...</i>" />
  <asp:RegularExpressionValidator runat="server" ControlToValidate="txtPassword"
           Display="Dynamic" ErrorMessage="<i>The string must be 20 characters or less...</i>"
           ValidationExpression="^.{1,20}$" />
  <br />
  <asp:Button runat="server" Text="View the String as Encrypted Text"
	OnClick="DisplayEncryptedText" />
  <p>
  <asp:Literal runat="server" id="ltlResults" />
</form>


[Return to the article]