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:
- using System.Security.Cryptography;
- // 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")));
- public string GenerateMD5(string yourString)
- {
- return string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(yourString)).Select(s => s.ToString("x2")));
- }
- var example = "This is a Test String"; // "This is a Test String"
- var hashed = GenerateMD5(example); // "7ae92fb767e5024552c90292d3cb1071"

Sonu ChaudharyPosted May 26, 2016, 10:33 AM
good one
Bhuvanesh MohankumarPosted May 6, 2016, 3:55 PM
Good one...
Bhuvanesh MohankumarPosted May 6, 2016, 3:55 PM
Good one...
Asfend YarPosted Mar 3, 2016, 3:37 PM
md5 and md3 what's the difference between these two ??
Asfend YarPosted Mar 3, 2016, 3:36 PM
nice share
Nemilidinne AshokreddyPosted Nov 21, 2015, 5:04 AM
Nice Information
Gowtham KPosted Oct 28, 2015, 10:59 AM
Nice Share
Mohammed IbrahimPosted Oct 28, 2015, 9:21 AM
nice
Sibeesh VenuPosted Oct 28, 2015, 7:28 AM
Nice Share
Former memberPosted Oct 28, 2015, 4:09 AM
What is the meaning of this line s.ToString("x2") ? what is x2 ? what other option available like x2? please come with detail. thanks
Nilesh JadavPosted Oct 27, 2015, 9:50 PM
Good Work !!