Home  [Bill's Home]

MD5 and SHA-1 (to Base-64)

MD5 and SHA-1 produces a hash signature, and the output is typically show in a hex format or a Base-64. In this example the output is converted into a Base-64 format. The following is an example:

Message

 

MD5

SHA-1

SHA-256

SHA-384

SHA-512

As a test, MD5 should give:

"Hello": ixqZU8RhEpaoJ6v4xHgE1w==
and "hello": XUFAKrxLKna5cZ2REBfFkg==

With SHA-1:

"Hello" should give: 9/+ei3uy4Jtwk1pdeF4MxdnQq/A=
"hello" should give: qvTGHdzF6KLavt4PO0gs2a6pQ00=

The code uses the Convert.ToBase64String() method to convert from a byte array to a Hash-64 string:

   1:  using System;
   2:  using System.Data;
   3:  using System.Configuration;
   4:  using System.Web;
   5:  using System.Web.Security;
   6:  using System.Web.UI;
   7:  using System.Web.UI.WebControls;
   8:  using System.Web.UI.WebControls.WebParts;
   9:  using System.Web.UI.HtmlControls;
  10:  using System.Collections;
  11:  using System.Security.Cryptography;
  12:   
  13:  public partial class _Default3 : System.Web.UI.Page
  14:  {
  15:      protected void Page_Load(object sender, EventArgs e)
  16:      {
  17:   
  18:      }
  19:      protected void Button3_Click(object sender, EventArgs e)
  20:      {
  21:          string message;
  22:   
  23:          message = this.tbMessage.Text;
  24:   
  25:          System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  26:   
  27:          MD5 md5 = new MD5CryptoServiceProvider();
  28:          SHA1 sha1 = new SHA1CryptoServiceProvider();
  29:          SHA256Managed sha256 = new SHA256Managed();
  30:          SHA384Managed sha384 = new SHA384Managed();
  31:          SHA512Managed sha512 = new SHA512Managed();
  32:   
  33:          byte[] messageBytes = encoding.GetBytes(message);
  34:   
  35:          byte[] hashmessage = md5.ComputeHash(messageBytes);
  36:   
  37:          this.tbMD5.Text = Convert.ToBase64String(hashmessage);
  38:   
  39:          hashmessage = sha1.ComputeHash(messageBytes);
  40:   
  41:          this.tbSHA1.Text = Convert.ToBase64String(hashmessage);
  42:   
  43:          hashmessage = sha256.ComputeHash(messageBytes);
  44:   
  45:          this.tbSHA256.Text = Convert.ToBase64String(hashmessage);
  46:   
  47:          hashmessage = sha384.ComputeHash(messageBytes);
  48:   
  49:          this.tbSHA384.Text = Convert.ToBase64String(hashmessage);
  50:   
  51:          hashmessage = sha512.ComputeHash(messageBytes);
  52:   
  53:          this.tbSHA512.Text = Convert.ToBase64String(hashmessage);
  54:   
  55:      }
  56:      public static string ByteToString(byte[] buff)
  57:      {
  58:          string sbinary = "";
  59:   
  60:          for (int i = 0; i < buff.Length; i++)
  61:          {
  62:              sbinary += buff[i].ToString("X2"); // hex format
  63:          }
  64:          return (sbinary);
  65:      }
  66:  }