Click here to Skip to main content
Click here to Skip to main content
Go to top

How To: Hash Data Using MD5 and SHA1

, 13 Aug 2009
Rate this:
Please Sign up or sign in to vote.
Sample application describing how to use the MD5 and SHA1 classes.

EncryptionSample

Introduction

My encryption methods take a string and hash it using MD5 or SHA1 and then return it encrypted.

There are two types of encryption:

  1. One way Encryption
  2. Take the input data and encrypt it, and there is no way to decrypt it again to get the source data. A good sample for one way encryption is MD5. Another good sample for one way encryption is SQL Server Membership; it store passwords encrypted and there is no way to get the original password back. All we can do is compare the password you entered and the hashed data.

  3. Two way Encryption
  4. Take input data and encrypt it, and in another side we take the encrypted data and decrypt it again using the same algorithm.

See samples here: http://waleedelkot.blogspot.com/2009/02/encryption-and-decryption-using-c.html.

In this article, I will talk about MD5 and SHA1 and present a sample code. The namespace we are using is: System.Security.Cryptography.

Advantages and Disadvantages

The following articles give a lot of detail on the differences of performance of the algorithms:

Important Information

MD5 (Message Digest Algorithm):

It was developed by Ronald Rivest in 1991. The hash size for the MD5 algorithm is 128 bits. The ComputeHash methods of the MD5 class returns the hash as an array of 16 bytes.

SHA1 (Secure Hash Algorithm):

This was developed by NIST. The hash size for the SHA1 algorithm is 160 bits.

Background

If you are familiar with C# and its security classes, this article will be easy for you.

Using the code

You can use the GetMD5HashData or GetSHA1HashData method directly to hash any string. I'm using the MD5 class and the SHA1 class.

The sample code contains four methods:

  • GetMD5HashData: takes any string and hashes it using the MD5 class.
  • GetSHA1HashData: takes any string and hashes it using the SHA1 class.
  • ValidateMD5HashData: compares input text using MD5 with the stored one.
  • ValidateSHA1HashData: compares input text using SHA1 with the stored one.

Hashing using the MD5 class

/// <summary>
/// take any string and encrypt it using MD5 then
/// return the encrypted data 
/// </summary>
/// <param name="data">input text you will enterd to encrypt it</param>
/// <returns>return the encrypted text as hexadecimal string</returns>
private string GetMD5HashData(string data)
{
    //create new instance of md5
    MD5 md5 = MD5.Create();

    //convert the input text to array of bytes
    byte[] hashData = md5.ComputeHash(Encoding.Default.GetBytes(data));

    //create new instance of StringBuilder to save hashed data
    StringBuilder returnValue = new StringBuilder();

    //loop for each byte and add it to StringBuilder
    for (int i = 0; i < hashData.Length; i++)
    {
        returnValue.Append(hashData[i].ToString());
    }

    // return hexadecimal string
    return returnValue.ToString();

}

Hashing using the SHA1 class

/// <summary>
/// take any string and encrypt it using SHA1 then
/// return the encrypted data
/// </summary>
/// <param name="data">input text you will enterd to encrypt it</param>
/// <returns>return the encrypted text as hexadecimal string</returns>
private string GetSHA1HashData(string data)
{
    //create new instance of md5
    SHA1 sha1 = SHA1.Create();

    //convert the input text to array of bytes
    byte[] hashData = sha1.ComputeHash(Encoding.Default.GetBytes(data));

    //create new instance of StringBuilder to save hashed data
    StringBuilder returnValue = new StringBuilder();

    //loop for each byte and add it to StringBuilder
    for (int i = 0; i < hashData.Length; i++)
    {
        returnValue.Append(hashData[i].ToString());
    }

    // return hexadecimal string
    return returnValue.ToString();
}

Validation methods

/// <summary>
/// encrypt input text using MD5 and compare it with
/// the stored encrypted text
/// </summary>
/// <param name="inputData">input text you will enterd to encrypt it</param>
/// <param name="storedHashData">the encrypted text
///         stored on file or database ... etc</param>
/// <returns>true or false depending on input validation</returns>
private bool ValidateMD5HashData(string inputData, string storedHashData)
{
    //hash input text and save it string variable
    string getHashInputData = GetMD5HashData(inputData);

    if (string.Compare(getHashInputData, storedHashData) == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/// <summary>
/// encrypt input text using SHA1 and compare it with
/// the stored encrypted text
/// </summary>
/// <param name="inputData">input text you will enterd to encrypt it</param>
/// <param name="storedHashData">the encrypted
///           text stored on file or database ... etc</param>
/// <returns>true or false depending on input validation</returns>

private bool ValidateSHA1HashData(string inputData, string storedHashData)
{
    //hash input text and save it string variable
    string getHashInputData = GetSHA1HashData(inputData);

    if (string.Compare(getHashInputData, storedHashData) == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

I hope my article was helpful for you all. Here is my blog: http://waleedelkot.blogspot.com/.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Waleed Elkot
Software Developer (Senior) Equinox Web
Egypt Egypt
I have 5 years experience working as a Software Developer. I have a wide range of experience in programming and I am skilled in the use of Visual Studio.NET 2008, Windows AppLication, Web Application, Web Services, Windows Services, WPF, HTML, Java Script, Ajax, ASP.NET, DevExpress Controls, Office Application Programmability in Visual Studio.NET 2008, creating web and windows applications using C#.NET and experienced in using all Microsoft Office Applications.

Comments and Discussions

 
QuestionWhere I put these code in my project? on login page or when i add a new user? Pinmemberisacgavrilas22-Sep-14 0:07 
QuestionNeed fixed length encrypted string output algorithm in c# ? PinmemberManivignesh20-May-14 1:36 
BugEncoding.Default !!! PinmemberDmitry Gusarov23-Nov-13 11:08 
QuestiontextBox2.Text... Pinmemberthomas4815-Sep-12 23:51 
GeneralMy vote of 5 PinmemberMmohmmad26-Jun-12 9:19 
GeneralMy vote of 5 Pinmembermanoj kumar choubey29-Mar-12 20:08 
QuestionHexadecimal formatting Pinmembermcb200327-Oct-11 11:49 
GeneralWhich is better Pinmemberhulkonline30-Aug-09 23:25 
GeneralRe: Which is better PinmemberWaleed Elkot30-Aug-09 23:51 
GeneralRe: Which is better PinmemberMark Woan10-Nov-09 9:34 
GeneralRe: Which is better PinmemberAli Hamdar12-Feb-10 11:01 
GeneralRe: Which is better PinmemberNWPU_Tbeck3-Dec-13 14:19 
GeneralSecurtiy Pinmemberhulkonline30-Aug-09 23:24 
GeneralNice Article PinmemberWael Hussein26-Aug-09 22:33 
GeneralRe: Nice Article PinmemberWaleed Elkot26-Aug-09 22:54 
GeneralMD5 Collision PinmemberHardy Wang24-Aug-09 2:02 
GeneralRe: MD5 Collision PinmemberWaleed Elkot26-Aug-09 22:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140922.1 | Last Updated 13 Aug 2009
Article Copyright 2009 by Waleed Elkot
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid