lotsoftools

C# MD5 Hash

Learn how to generate the MD5 hash of a string in C#. This snippet provides a simple and efficient way to do it.

using System; using System.Text; using System.Security.Cryptography; namespace Sample { class Program { static void Main(string[] args) { string source = 'Hello World!'; using (MD5 md5Hash = MD5.Create()) { string hash = GetMd5Hash(md5Hash, source); Console.WriteLine('The MD5 hash of ' + source + ' is: ' + hash + '.'); } } static string GetMd5Hash(MD5 md5Hash, string input) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString('x2')); } return sBuilder.ToString(); } } }

This C# snippet starts by defining the string whose MD5 hash will be generated. It then creates an instance of the MD5 class and calls the 'GetMd5Hash' method.

The 'GetMd5Hash' method takes as arguments the MD5 instance and the input string. It then converts the string into a byte array and computes the hash.

Finally, it concatenates each byte of the hash into a new string and returns it. The MD5 hash of the source string is printed in the console.