MD5 hashing in C#

Here is the Encrypt function for MD5 hashing that i have coded. I hope it is useful for you.

using System.Security.Cryptography;

public class MD5Algorithm
{
    /// <summary>
    /// Encrypts specified text using MD5 algorithm and returns a 32 character hexadecimal string.
    /// </summary>
    /// <param name="text">Text value to be encrypted.</param>
    /// <returns>Encrypted value formatted as a 32 character hexadecimal string..</returns>
    public string Encrypt(string text)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

        // Convert the text to a byte array and compute the hash.
        byte[] hashed = md5.ComputeHash(Encoding.UTF8.GetBytes(text));

        // Create a new Stringbuilder to collect the bytes and create a string.
        StringBuilder stringBuilder = new StringBuilder();

        // Loop through each byte of the hashed data and format each one as a hexadecimal string.
        for (int i = 0; i < hashed.Length; i++)
        {
            stringBuilder.Append(hashed[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return stringBuilder.ToString();

    }
}
example usage :
string hashed = new MD5Algorithm().Encrypt("hash me!");

1 comments:

traininginstitute said...

I think this is a really good article. You make this information interesting and engaging. You give readers a lot to think about and I appreciate that kind of writing.
data science training

Post a Comment