Common encryption and decryption methods in C# (MD5 encryption and decryption)

There are many common encryption and decryption methods in C#, including the MD5 method. Here is an example of using C# for MD5 encryption and decryption:

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

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

        // MD5加密
        string md5Hash = MD5Hash(originalText);
        Console.WriteLine("MD5 Hash: " + md5Hash);

        // MD5验证
        bool md5Verify = VerifyMD5Hash(originalText, md5Hash);
        Console.WriteLine("MD5 Verify: " + md5Verify);
    }

    // 使用MD5加密字符串
    public static string MD5Hash(string text)
    {
        using (MD5 md5 = MD5.Create())
        {
            byte[] inputBytes = Encoding.ASCII.GetBytes(text);
            byte[] hashBytes = md5.ComputeHash(inputBytes);

            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                builder.Append(hashBytes[i].ToString("x2"));
            }
            return builder.ToString();
        }
    }

    // 验证MD5哈希值
    public static bool VerifyMD5Hash(string text, string hash)
    {
        string hashOfText = MD5Hash(text);

        StringComparer comparer = StringComparer.OrdinalIgnoreCase;
        return comparer.Compare(hashOfText, hash) == 0;
    }
}

In the above example, the MD5Hash function encrypts the input string using the MD5 algorithm and returns the result in hexadecimal string format. The VerifyMD5Hash function is used to check if the MD5 hash value of the input string matches the provided hash value.

Note: MD5 is a hashing algorithm that is irreversible. Therefore, the result of MD5 encryption cannot be decrypted back to the original string. MD5 is typically used to verify the integrity of data rather than encrypt sensitive information.

bannerAds