Generate MD5 hash of a string in C#
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 –
- Initialize the MD5 hash object with
MD5.Create()method. - Convert the given string into a byte array using the
Encoding.GetBytes()method. - Compute the hash value for the specified byte array with the
ComputeHash()method. - 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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System; using System.Text; using System.Security.Cryptography; public class Example { static string ComputeMD5(string s) { StringBuilder sb = new StringBuilder(); // Initialize a MD5 hash object using (MD5 md5 = MD5.Create()) { // Compute the hash of the given string byte[] hashValue = md5.ComputeHash(Encoding.UTF8.GetBytes(s)); // Convert the byte array to string format foreach (byte b in hashValue) { sb.Append($"{b:X2}"); } } return sb.ToString(); } public static void Main() { string hash = ComputeMD5("Hello"); Console.WriteLine(hash); // 8B1A9953C4611296A827ABF8C47804D7 } } |
Here’s an even shorter version of the above code that uses the BitConverter.ToString() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Text; using System.Security.Cryptography; public class Example { static string ComputeMD5(string s) { using (MD5 md5 = MD5.Create()) { return BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(s))) .Replace("-", ""); } } public static void Main() { string hash = ComputeMD5("Hello"); Console.WriteLine(hash); // 8B1A9953C4611296A827ABF8C47804D7 } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Text; using System.Security.Cryptography; public class Example { static string ComputeMD5(string s) { using (MD5 md5 = MD5.Create()) { byte[] hashValue = md5.ComputeHash(Encoding.UTF8.GetBytes(s)); return Convert.ToHexString(hashValue); } } public static void Main() { string hash = ComputeMD5("Hello"); Console.WriteLine(hash); // 8B1A9953C4611296A827ABF8C47804D7 } } |
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#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)