CSharp .Net Tutorial: MD5 Hash Encryption

James Cloud
Introduction

There are many different and varying forms of encryption used in computer security. Some of the more popular include base64, RC4, hashing, and passwords. One of the most resilient and reliable of these is the MD5 Hash. In the steps below, you will learn how to create a function that will intake a string value, convert that value into a MD5 hash, and output the results as a string.

Step One - Necessary Includes

Before you can create the string to MD5 conversion function you will need to include a reference to 'System.Security.Cryptography' in your project. Add this source code to your projects includes,

using System.Security.Cryptography;

With the proper includes in place, proceed to step two.

Step Two - String to MD5

It is time to make a new string function called, 'String2MD5', which will be used to convert a given string into a MD5 hash. Using the code given below, create a new string function.

private String String2MD5(String strString)
{
// Create a New Hash
MD5 md5Hash = MD5.Create();

// Covert the String to Bytes
byte[] BytesIn = Encoding.ASCII.GetBytes(strString);

// Create a Hash from the Bytes
byte[] BytesOut = md5Hash.ComputeHash(BytesIn);

// Create a New String Builder
StringBuilder stringBuilder = new StringBuilder();
for (int j = 0; j < BytesOut.Length; j++)
{
stringBuilder.Append(BytesOut[j].ToString("X2"));
}

// Return the MD5 Hash
return stringBuilder.ToString();
}

To encrypt a string into a MD5 hash, call the 'String2MD5()' void and supply the string as the parameter. The function will return the resulting MD5 hash in string format.

Conclusion

What this function does, essentially, is it takes the first parameter(strString), changes that into a byte array, and then, using the .Net framework's Cryptography MD5 object, converts the new byte array into a hash. It then takes the newly created hash, converts that into to a string, and then finally outputs the final hash string result.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.