Implementing MD5 encryption in C#

In C#, you can utilize the MD5CryptoServiceProvider class in the System.Security.Cryptography namespace to implement MD5 encryption. Here is an example code:

using System;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main()
    {
        string originalText = "Hello, World!";

        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(originalText);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString("x2")); // x2表示以16进制形式输出
            }

            string encryptedText = sb.ToString();
            Console.WriteLine("Original Text: {0}", originalText);
            Console.WriteLine("Encrypted Text: {0}", encryptedText);
        }
    }
}

Output result:

Original Text: Hello, World!
Encrypted Text: ed076287532e86365e841e92bfc50d8c

In the above code, an MD5 instance is created first, then the original text to be encrypted is converted to a byte array, and the ComputeHash method is used to calculate the MD5 hash value. Finally, the hash value is converted to a hexadecimal string and outputted.

bannerAds