Password Encryption using MD5 Hash Algorithm in C#

Simple way to hash sensitive string

It’s really bad if someone knew your password. As a developer or web master or something else, we have an ethic that we also don’t want to see other’s password. So, what we need to do to store those passwords? One simple solution is using hash function. We change the readable password into unreadable text and no one, even yourself, can’t decrypt that text ever. One of the popular (or simple) method is MD5 Hash Algorithm.

How does MD5 Hash Algorithm Works? The point is this algorithm change your password into 32 hexadecimal digits. It doesn’t care how long is your password and it’ll become 32 hexadecimal digits.  For complete explanation please read this wikipedia article.

The next question is, how can we do that? That’s a simple question. Because I’m a .NET developer, I will show you how easy to implement MD5 hash algorithm using .NET Cryptography Framework.

Okay, here is the code that you can use to generate MD5 Hash:

using System.Text;  
using System.Security.Cryptography;  

namespace CryptoLib  
{  
  public static class Encryptor  
  {  
    public static string MD5Hash(string text)  
    {  
      MD5 md5 = new MD5CryptoServiceProvider();  

      //compute hash from the bytes of text  
      md5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(text));  
  
      //get hash result after compute it  
      byte[] result = md5.Hash;  

      StringBuilder strBuilder = new StringBuilder();  
      for (int i = 0; i < result.Length; i++)  
      {  
        //change it into 2 hexadecimal digits  
        //for each byte  
        strBuilder.Append(result[i].ToString("x2"));  
      }  

      return strBuilder.ToString();  
    }  
  }  
}

I use that function and try it in my WPF Application and here is the result:

WPF MD5 Implementation
WPF MD5 Implementation

Okay, that’s all I got this time. Hope this simple tutorial helps you. See you on my next post.

References

Generating MD5 Hash out of C# Objects - CodeProject

*Cover Photo by Jess Watters on Unsplash.


Except as otherwise noted, the article of this page is licensed under the Creative Commons Attribution 4.0 International License. Code samples are licensed under the MIT License.

Hello there, thanks for reading. Did you find this writing helpful, or save your valuable time? If so, you can support me by sending a cup of coffee with the button right here — you'll have my eternal gratitude!

Buy Me A Coffee