Generating an MD5 Hash from a String Using LINQ

While working on another blog post, I encountered the need to generate a MD5 hash by passing in a string value and didn’t see any very appealing solutions off-hand that didn’t involve iterating through a loop. I elected to visit everyone’s favorite friend LINQ to easily handle this issue.

The Problem

You need to generate an MD5 hash using a string, but you want a quick and easy way to do it.

The Solution

Firstly, you will need to ensure that you are referencing the appropriate namespace (System.Security.Cryptography) to work with MD5 hashes by adding the following using statement :

using System.Security.Cryptography;

Now, just use the following LINQ statement that will allow you to pass in your value and generate an MD5 hash of the string :

//Your string value
string yourStringValue = "This is a test";
//Generate a hash for your strings (this appends each of the bytes of the value into a single hashed string
var hashValue = string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(yourStringValue)).Select(s => s.ToString("x2")));

Or if you would prefer it as a method :

public string GenerateMD5(string yourString)
{
       return string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(yourString)).Select(s => s.ToString("x2")));
}

Example :

var example = "This is a Test String"; //"This is a Test String"
var hashed = GenerateMD5(example);     //"7ae92fb767e5024552c90292d3cb1071"
About these ads

3 thoughts on “Generating an MD5 Hash from a String Using LINQ

  1. Pingback: Prevent Repeated Requests using ActionFilters in ASP.NET MVC | rionscode

  2. Pingback: Creating Advanced Audit Trails using ActionFilters in ASP.NET MVC | rionscode

  3. Do you mind if I quote a few of your posts as long as I
    provide credit and sources back to your site? My blog
    site is in the very same niche as yours and my visitors would genuinely benefit from a
    lot of the information you provide here. Please let me know if this okay with you.
    Cheers!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s