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 wasn’t really in the mood for loops. I elected to see if LINQ could make the process a bit easier.

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 System.Security.Cryptography namespace to work with MD5 hashes by adding the following using statement:

  1. 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:
  1. // Your string value  
  2. string yourStringValue = "This is a test";   
  3. // Generate a hash for your strings (this appends each of   
  4. // the bytes of the value into a single hashed string  
  5. 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:
  1. public string GenerateMD5(string yourString)   
  2. {  
  3.    return string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(yourString)).Select(s => s.ToString("x2")));  
  4. }  
You can see an example of this below:
  1. var example = "This is a Test String"// "This is a Test String"   
  2. var hashed = GenerateMD5(example); // "7ae92fb767e5024552c90292d3cb1071"  


Similar Articles