This post will discuss how to generate the MD5 hash of a string in C#.

In C#, you can use the MD5 class from System.Security.Cryptography namespace to compute the MD5 hash of the input data. Following are the steps to calculate the MD5 hash value of a string –

  1. Initialize the MD5 hash object with MD5.Create() method.
  2. Convert the given string into a byte array using the Encoding.GetBytes() method.
  3. Compute the hash value for the specified byte array with the ComputeHash() method.
  4. Transform the byte array to produce a 32-character, hexadecimal-formatted hash string.

 
The following example demonstates this by calculating the SHA-256 hash for a given string.

Download  Run Code

 
Here’s an even shorter version of the above code that uses the BitConverter.ToString() method:

Download  Run Code

 
If you’re using .NET 5 and above, you can use the Convert.ToHexString() method to convert the byte array to its equivalent string representation.

Download  Run Code

 
Important Note: To avoid collision problems associated with the MD5 hash, Microsoft recommends using the SHA-256 hash (or SHA-512 hash) over MD5.

That’s all about generating the MD5 hash of a string in C#.