Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#

How To: Hash Data Using MD5 and SHA1

Rate me:
Please Sign up or sign in to vote.
4.79/5 (25 votes)
13 Aug 2009CPOL2 min read 211K   8.7K   52   18
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

C#
/// <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

C#
/// <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

C#
/// <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)


Written By
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

 
SuggestionDo not use 'Encoding.Default' in the code Pin
@cromx21-Jun-15 22:37
@cromx21-Jun-15 22:37 
Yes, as the title says - don't use it

Instead of using Encoding.Default, use Encoding.UTF8 or Encoding.UTF16.
If you're curious what's the difference between UTF8 and UTF16 then click me.

modified 22-Jun-15 4:45am.

QuestionWhere I put these code in my project? on login page or when i add a new user? Pin
isacgavrilas22-Sep-14 0:07
isacgavrilas22-Sep-14 0:07 
QuestionNeed fixed length encrypted string output algorithm in c# ? Pin
Manivignesh20-May-14 1:36
Manivignesh20-May-14 1:36 
BugEncoding.Default !!! Pin
Dmitry Gusarov23-Nov-13 11:08
Dmitry Gusarov23-Nov-13 11:08 
QuestiontextBox2.Text... Pin
thomas4815-Sep-12 23:51
thomas4815-Sep-12 23:51 
GeneralMy vote of 5 Pin
Mmohmmad26-Jun-12 9:19
Mmohmmad26-Jun-12 9:19 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey29-Mar-12 20:08
professionalManoj Kumar Choubey29-Mar-12 20:08 
QuestionHexadecimal formatting Pin
mcb2k327-Oct-11 11:49
mcb2k327-Oct-11 11:49 
GeneralWhich is better Pin
hulkonline30-Aug-09 23:25
hulkonline30-Aug-09 23:25 
GeneralRe: Which is better Pin
Waleed Elkot30-Aug-09 23:51
Waleed Elkot30-Aug-09 23:51 
GeneralRe: Which is better Pin
Mark Woan10-Nov-09 9:34
Mark Woan10-Nov-09 9:34 
GeneralRe: Which is better Pin
Ali Hamdar12-Feb-10 11:01
Ali Hamdar12-Feb-10 11:01 
GeneralRe: Which is better Pin
NWPU_Tbeck3-Dec-13 14:19
NWPU_Tbeck3-Dec-13 14:19 
GeneralSecurtiy Pin
hulkonline30-Aug-09 23:24
hulkonline30-Aug-09 23:24 
GeneralNice Article Pin
Wael Hussein26-Aug-09 22:33
Wael Hussein26-Aug-09 22:33 
GeneralRe: Nice Article Pin
Waleed Elkot26-Aug-09 22:54
Waleed Elkot26-Aug-09 22:54 
GeneralMD5 Collision Pin
Hardy Wang24-Aug-09 2:02
Hardy Wang24-Aug-09 2:02 
GeneralRe: MD5 Collision Pin
Waleed Elkot26-Aug-09 22:55
Waleed Elkot26-Aug-09 22:55 

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

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